In this article we will learn how to check if set is empty in JavaScript.
It is very common to check if set is empty in JavaScript in JavaScript.
Problem
Now we have a problem which is that we want to check if set is empty.
Imagine we have set like this:
const set = new Set([1, 2, 3, 4]);
And we want to check if this set is empty or not.
Expected Output
false
How to solve this problem?
The solution to this problem is easy, and fortunately, there is a built-in function in the set
that calculates the number of elements in the set
, called size()
.
Check if set is empty using size
method
As we said before, we can use size()
method to check if set is empty or not.
Example
const set = new Set([1, 2, 3, 4]);
if (set.size === 0) {
console.log('Set is empty');
console.log(true);
} else {
console.log('Set is not empty');
console.log(false);
}
Output
Set is not empty
false
Well, now you will probably use these codes more than once, so let's do a function called isEmpty
.
function isEmpty(set) {
// If set is empty
if (set.size === 0) {
return true;
}
// Otherwise
return false;
}
const set1 = new Set([1, 2, 3, 4]);
const set2 = new Set([]);
console.log(isEmpty(set1));
console.log(isEmpty(set2));
Output
false
true
Thank you for reading
Thank you for reading my blog. 🚀