How to get the Length of a Map in JavaScript

avatar

Borislav Hadzhiev

Tue Oct 19 20211 min read

banner

Photo by Zack Minor

Get the Length of a Map in JavaScript #

Use the size property to get the length of a Map - map.size. The size property returns the number of elements in the Map object. When accessed on an empty Map, the size property returns 0.

index.js
const map = new Map(); map.set('name', 'Tom'); map.set('age', 30); map.set('country', 'Chile'); console.log(map.size); // ๐Ÿ‘‰๏ธ 3

We used the Map.size property to get the number of key-value pairs the Map stores.

The property is very similar to an array's length property and returns an integer representing how many items the Map contains.

As opposed to the array's lenth property, the size property is read-only and can't be changed by the user.

index.js
const map = new Map(); map.set('name', 'Tom'); console.log(map.size); // ๐Ÿ‘‰๏ธ 1 map.size = 5; console.log(map.size); // ๐Ÿ‘‰๏ธ 1

Even though we tried to set the size of the Map, we were unable to. This is not the case when using the array's length property.

index.js
const arr = ['a', 'b', 'c']; console.log(arr.length); // ๐Ÿ‘‰๏ธ 3 arr.length = 1; console.log(arr.length); // ๐Ÿ‘‰๏ธ 1

Further Reading #

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee