In JavaScript, the Set constructor is used to create a new Set object. A Set is a built-in object in JavaScript that allows you to store unique values, whether they are primitive values or object references. The Set constructor is called with the new
keyword to create an instance of a Set.
Syntax:
let mySet = new Set([iterable]);
Parameters:
-
mySet
: The variable that will reference the newly created Set instance. -
iterable
(optional): An iterable (such as an array) whose elements are used to initialize the Set. If not provided, an empty Set is created.
Example: In this example, we will see that the 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 } }