In this article we will learn how to get the length of a set.
It is very common to get the length of a set in JavaScript.
Problem
Sometimes you have to know how many elements are in the set, 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 set elements.
Imagine you have a set like this:
const set = new Set([1, 2, 3, 4]);
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 set to know the number of elements called size
.
Get length of set using size
We can use size
property to get the length of a set.
Example
// set
const set = new Set([1, 2, 3, 4]);
// Result:
console.log(set.size);
Output
4
Get length of set using forEach
We can use forEach
to get the length of a set as well.
Example
const set = new Set([1, 2, 3, 4]);
let length = 0;
set.forEach(ele => {
length++;
});
console.log(length);
Output
4
Thank you for reading
Thank you for reading my blog. 🚀