Skip to content

JavaScript Set contains | Example

  • by

Use set has() method to check specified value Set contains or not in JavaScript. It returns true if the specified value is present, otherwise false.

setObj.has(value)  

JavaScript Set contains

A simple example code set has JavaScript.

<!DOCTYPE html>
<html>
<body>

  <script>
   const set1 = new Set([1, 2, 3, 4, 5]);

   console.log(set1.has(1));

   console.log(set1.has(5));

   console.log(set1.has(6));
 </script>
</body>
</html>

Output:

JavaScript Set contains

More examples

const mySet = new Set();
mySet.add('foo');

mySet.has('foo');  // returns true
mySet.has('bar');  // returns false

const set1 = new Set();
const obj1 = {'key1': 1};
set1.add(obj1);

set1.has(obj1);        // returns true
set1.has({'key1': 1}); // returns false because they are different object references
set1.add({'key1': 1}); // now set1 contains 2 entries

Checking if a Set contains a list in JavaScript

You can’t compare references like arrays and objects for equality (you can compare values, though).

The way you’re doing it, you’re checking against a different reference, even though the values appear to be the same.

Do something like this:

var a = new Set();
var b = [1];

a.add(b);

a.has(b); // => true

Do comment if you have any doubts or suggestions on this Js set topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *