You can use the size
property to get the length of a Map
object. The size
property returns the number of elements in the Map
object.
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 returns an integer value representing how many entries the Map
object has.
Unlike the array's length
property, the map's size
property is read-only and can not be changed:
const map = new Map([
['name', 'Atta'],
['age', 34]
])
console.log(map.size) // 2
map.size = 6
console.log(map.size) // 2 --> Remains the same
This is not the case with the length
property of the array, which is writeable and can be set to a new value to increase or decrease the size of the array:
const numbers = [1, 2, 3, 4]
// Truncate to 3-element
numbers.length = 3
console.log(numbers)
// [1, 2, 3]
// Increase size to 5
numbers.length = 5
console.log(numbers)
// [ 1, 2, 3, <2 empty items> ]
Read this article to learn more about the Map
object and how to create collections of key-value pairs in JavaScript.
✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.