How to check if a Map is Empty in JavaScript

avatar

Borislav Hadzhiev

Wed Oct 27 20211 min read

banner

Photo by Brannon Naito

Check if a Map is Empty in JavaScript #

Use the size property to check if a Map is empty, e.g. map.size === 0. The size property returns the number of elements in the Map. When accessed on an empty Map, the size property returns 0.

index.js
const map1 = new Map(); console.log(map1.size); // ๐Ÿ‘‰๏ธ 0 if (map1.size === 0) { // ๐Ÿ‘‡๏ธ this runs console.log('โœ… map is empty'); } else { console.log('โ›”๏ธ map is not empty'); } const map2 = new Map(); map2.set('country', 'Chile'); console.log(map2.size); // ๐Ÿ‘‰๏ธ 1

We used the size property on the Map to check if it's empty.

The property returns the number of elements the Map stores.

The property is very similar to an array's length property, however it's read only and cannot be changed.

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

Even though we attempted to set the size property on the Map, we were unable to.

This behavior is different when working with arrays.

index.js
const arr = ['a', 'b', 'c']; console.log(arr.length); // ๐Ÿ‘‰๏ธ 3 arr.length = 1; console.log(arr.length); // ๐Ÿ‘‰๏ธ 1 console.log(arr); // ๐Ÿ‘‰๏ธ ['a']
As opposed to the Map's size property we were able to change the array's length.

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