In this article we will learn how to get the length of a map.
It is very common to get the length of a map in JavaScript.
Problem
Sometimes you have to know how many elements are in the map, because depending on the number some lines of code can execute
Therefore, in this lesson, we will explain how to find out the number of map elements.
Imagine you have a map like this:
const map = new Map([
['name', 'John'],
['age', 30],
]);
// Map(2) { 'name' => 'John', 'age' => 30 }
If I asked you how many elements there were, how many would you say? two right?
But you knew through your human brain, but how do we know that through the code.
Fortunately, there is a function in the map to know the number of elements called size
.
Get length of map using size
We can use size
property to get the length of a map.
Example
// Map
const map = new Map([
['name', 'John'],
['age', 30],
]);
// Result:
console.log(map.size);
Output
2
Get length of map using forEach
We can use forEach
to get the length of a map as well.
Example
const map = new Map([
['name', 'John'],
['age', 30],
]);
let length = 0;
map.forEach(ele => {
length++;
});
console.log(length);
Output
2
Thank you for reading
Thank you for reading my blog. 🚀