Skip to content

JavaScript set has() | Method

  • by

JavaScript set has() method is used to check whether the Set object contains the specified value or not. This method returns a boolean indicating whether an element with the specified value exists in a Set object or not.

setObj.has(value)

JavaScript has() method

Simple example code.

<!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 has Method

Checking if a Set contains a list in JavaScript

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

a.add(b);

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

More example

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

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

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

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading