Borislav Hadzhiev
Wed Oct 27 2021·1 min read
Photo by Brannon Naito
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
.
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.
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.
const arr = ['a', 'b', 'c']; console.log(arr.length); // 👉️ 3 arr.length = 1; console.log(arr.length); // 👉️ 1 console.log(arr); // 👉️ ['a']
size
property we were able to change the array's length
.