Open In App

JavaScript Set() Constructor

Last Updated : 24 Mar, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

The Javascript Set constructor is used to create Set objects. It will create a set of unique values of any type, whether primitive values or object preferences. It returns the new Set object. It mainly helps in creating a new set of objects which contains unique elements.

Syntax:

new Set()
new Set(iterable)

Parameters: This method accepts a single parameter that is described below:

  • iterable: If an object is passed, all values will be added to the new set. If the parameter is not specified then the new set is empty.

Return Value: This method returns a new Set object.

Example 1: In this example, we will see how to create a new Set object.

Javascript




const mySet = new Set();
  
mySet.add("California");
mySet.add("India");
mySet.add("Russia");
mySet.add(10);
  
const myObject = { a: 1, b: 8 };
  
mySet.add(myObject);
  
console.log(mySet);


Output:

Set(5) { 'California', 'India', 'Russia', 10, { a: 1, b: 8 } }

Example 2: In this example, we will see that set takes only a unique value.

Javascript




const mySet = new Set();
  
mySet.add("California");
mySet.add("India");
mySet.add("California");
mySet.add(10);
mySet.add(10);
  
const myObject = { a: 1, a: 5 };
  
mySet.add(myObject);
  
console.log(mySet);


Output:

Set(4) { 'California', 'India', 10, { a: 5 } }

In this example, we have added two times “California” and 10 but it creates a set with unique values.

We have a complete list of Javascript Set methods, to check those please go through this Sets in JavaScript article.

Supported Browser:

  • Chrome 38
  • Edge 12
  • Firefox 13
  • Opera 25
  • Safari 8

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads