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: 3Conclusion
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.