JavaScript Set() Constructor (original) (raw)
Last Updated : 12 Jul, 2024
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 Browsers:
- Chrome
- Edge
- Firefox
- Opera
- Safari