Borislav Hadzhiev
Reading timeยท2 min
Photo from Unsplash
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'); }
We used the
size
property on the Map
to check if it's empty.
The property returns the number of elements the Map
stores.
const map2 = new Map(); map2.set('country', 'Chile'); console.log(map2.size); // ๐๏ธ 1
The property is very similar to an array's length
property, however, it is
read-only and cannot be changed.
const map = new Map(); map.set('country', 'Chile'); console.log(map.size); // ๐๏ธ 1 // โ๏ธ TypeError: Cannot set property size of #<Map> which has only a getter map.size = 5;
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
.We set the array's length to 1
which automatically removed the last 2 elements
from the array.
Map objects also have keys()
and values()
methods.
const map1 = new Map(); map1.set('name', 'bobby hadz'); map1.set('country', ['Chile', 'ab']); map1.set('age', 30); const keys = [...map1.keys()]; console.log(keys.length); // ๐๏ธ 3 console.log(keys.length === 0); // ๐๏ธ false const values = [...map1.values()]; console.log(values.length); // ๐๏ธ 3 console.log(values.length === 0); // ๐๏ธ false
The
Map.keys
method returns an iterator object that contains the keys of the Map
.
The
Map.values
method returns an iterator object containing the values for each element in the
Map
.
We used the spread syntax (...) to convert the iterator objects to an array and
accessed the length
property on the arrays to check if the Map
is empty.
However, using the size
property on the Map
object is more convenient and
direct.
If you need to empty a Map
object, use the Map.clear()
method.
const map1 = new Map(); map1.set('name', 'bobby hadz'); map1.set('country', ['Chile', 'ab']); map1.set('age', 30); console.log(map1.size); // ๐๏ธ 3 map1.clear(); console.log(map1.size); // ๐๏ธ 0 console.log(map1); // ๐๏ธ Map(0) {}
The Map.clear method removes all elements from a Map object.
If you have to check if a Map
object is empty often, define a reusable
function.
function mapIsEmpty(map) { return map.size === 0; } // ๐๏ธ false console.log( mapIsEmpty( new Map([ ['name', 'bobby'], ['age', 30], ]), ), ); // ๐๏ธ true console.log(mapIsEmpty(new Map()));
The mapIsEmpty()
function takes a Map
object as a parameter and returns
true
if it is empty and false
otherwise.