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 = {};


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

JavaScript Set add object

Simple example code.

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

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




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

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