How to check if a Map is Empty in JavaScript

avatar

Borislav Hadzhiev

Last updated: Sep 7, 2022

banner

Photo from Unsplash

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 #

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.