How to Get the Length (Size) of a Map in JavaScript
The Map object is a powerful data structure for storing key-value pairs, and a fundamental operation is to determine how many entries it contains. Unlike arrays which use the .length property, Map objects have a specific property for this purpose: .size.
This guide will teach you how to use the .size property to get the number of key-value pairs in a Map and explain its key differences from an array's .length property.
The Core Method (Recommended): map.size
The Map.prototype.size property is the standard, built-in way to get the number of elements in a Map. It returns an integer representing the count of key-value pairs.
For example, you have a Map and you want to know how many entries it holds.
// Problem: How to get the number of elements in this Map?
const userRoles = new Map([
['user1', 'admin'],
['user2', 'editor'],
['user3', 'viewer'],
]);
This .size property is all you need as solution:
const userRoles = new Map([
['user1', 'admin'],
['user2', 'editor'],
['user3', 'viewer'],
]);
const mapSize = userRoles.size;
console.log(mapSize); // Output: 3
If the Map is empty, .size will correctly return 0.
::
How the .size Property Works
The .size property is a "getter" that is automatically updated whenever you modify the Map. It provides a live, accurate count of the elements.
const myMap = new Map();
console.log(myMap.size); // Output: 0
// Add elements
myMap.set('a', 1);
myMap.set('b', 2);
console.log(myMap.size); // Output: 2
// Remove an element
myMap.delete('a');
console.log(myMap.size); // Output: 1
// Clear all elements
myMap.clear();
console.log(myMap.size); // Output: 0
A Crucial Distinction: .size vs. Array.prototype.length
While they serve a similar purpose, there is a key difference between a Map's .size and an Array's .length.
map.sizeis read-only. You cannot change the number of elements in aMapby setting itssizeproperty.const myMap = new Map([['a', 1]]);
myMap.size = 5; // This has no effect
console.log(myMap.size); // Output: 1array.lengthis writable. You can change an array by setting itslength. Setting it to a smaller number will truncate the array.const myArray = [1, 2, 3, 4, 5];
myArray.length = 2;
console.log(myArray); // Output: [1, 2]
This read-only nature of .size makes Maps more predictable and less prone to accidental mutation.
Conclusion
For getting the number of key-value pairs in a Map, the solution is simple and direct.
- The
map.sizeproperty is the only correct and recommended best practice. - It provides a read-only, live count of the elements in the
Map. - Avoid manual counting methods (like using
forEachand a counter), as the.sizeproperty is the most efficient and idiomatic solution.