The size property can be used to determine the length of a Map object. It returns the number of elements present in the Map.

const map = new Map()

console.log(map.size) // 0

map.set('name', 'Atta')
map.set('age', 34)

console.log(map.size) // 2

The size property provides an integer value representing the number of entries in the Map object.

Unlike the length property of an array, which can be found here, the size property of a map is read-only and cannot be modified:

const map = new Map([
  ['name', 'Atta'],
  ['age', 34]
])

console.log(map.size) // 2

map.size = 6

console.log(map.size) // 2 --> Remains the same

In contrast, the length property of an array is writable and can be assigned a new value to increase or decrease the size of the array:

const numbers = [1, 2, 3, 4]

// Truncate to a 3-element array
numbers.length = 3

console.log(numbers)
// [1, 2, 3]

// Increase the size to 5
numbers.length = 5

console.log(numbers);
// [1, 2, 3, <2 empty items>]

To learn more about the Map object and how to create collections of key-value pairs in JavaScript, you can refer to this article.

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.