Skip to content

JavaScript Set add object | Example code

  • by

Using the set add() method you can add objects to the set in JavaScript. The add() method inserts a new element with a specified value into a Set object.

Set of objects

let s = new Set();
let a = {};
let b = {};

s.add(a);

console.log(s.has(a));  // true
console.log(s.has(b));  // false

JavaScript Set add object

Simple example code.

<!DOCTYPE html>
<html>
<body>
  <script>
    let mySet = new Set()

    let person_obj = {f:"John", l:"Doe", age:25};

    mySet.add(person_obj)
    console.log(mySet)

  </script>
</body>
</html>

Output:

JavaScript Set add object

Add an array of values to a Set

While Set API is still very minimalistic, you can use Array.prototype.forEach and shorten your code a bit:

array.forEach(item => mySet.add(item))

// alternative, without anonymous arrow function
array.forEach(mySet.add, mySet)

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

Leave a Reply

Discover more from Tutorial

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

Continue reading