Skip to content

How to Get the Length (Size) of a Map in JavaScript

Learn how to check the number of key-value pairs in a JavaScript Map using the built-in .size property and understand its key differences from an array's .length.

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 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

Conclusion

For getting the number of key-value pairs in a Map, the solution is simple and direct.

  • The map.size property 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 forEach and a counter), as the .size property is the most efficient and idiomatic solution.
Navigation