These are the following ways to check whether the given set is empty or not:
1. Using size property - Mostly used
The size property is used to get the size of the set. if it returns 0 then the set will be empty else it has some elements.
let s = new Set();
if (s.size === 0)
console.log("Empty set")
else console.log("Not empty set")
// Let us add an item to check for a non-empty set
s.add(1);
if (s.size === 0)
console.log("Empty set")
else console.log("Not empty set")
Output
Empty set Not empty set
2. Using Lodash _.isEmpty() Method
The Lodash is JavaScript library, that provide the _.isEmpty() Method, that checks whether the given set is empty or not and returns the boolean value.
Note: The function can take any value as a parameter to check, it is not limited to set only.
const _ = require("lodash");
let s = new Set();
if (_.isEmpty(s) === true)
{ console.log("Empty set") }
else { console.log("Not empty set") }
Output:
Empty set3. Using Array.from() Method and length Property
The Array.from() method returns an array from any object with a length property. so it helps us to access the length property so that we can check its emptiness. This method does not alt the original object.
let s = new Set();
s.add(1);
if(Array.from(s).length === 0)
{ console.log("Empty set") }
else {console.log("Not empty set") }
Output
Not empty set