How to check if a set has specific element - JS

Mo Ibra

Mo Ibra

Dec 22, 2022

In this article we will learn how to check if set has specific element.

It is very common to check if set has specific element in JavaScript.


Problem

Sometimes you need to know if a certain element is in the set or not, and then execute certain code.

Imagine you have a set like this:

const set = new Set([1, 2, 3, 4]);

console.log(set);
// Set(4) { 1, 2, 3, 4 }

And you want to know if a specific element exists or not

How to solve this problem?

Fortunately, there is a built-in function in the set that determines whether there is a specific element in the set or not called has.

has method returns true or false.

Solution

As we said before, we can use has method to solve our problem.

// set
const set = new Set([1, 2, 3, 4]);

// Checking..
console.log(set.has(1));
console.log(set.has(2));
console.log(set.has(3));
console.log(set.has(100));

Think for a second and expect the result!

Output

true
true
true
false

The has() method returns a boolean indicating whether an element with the specified value exists in a Set object or not. (Source: MDN)


Thank you for reading

Thank you for reading my blog. 🚀

Suggestions For More Articles: