JavaScript Set()
Syntax & Examples
Set constructor
The Set constructor in JavaScript is used to create a new Set object. A Set is a collection of unique values, which can be of any type.
Syntax of Set
There are 2 variations for the syntax of Set() constructor. They are:
new Set()This constructor creates an empty Set object.
Returns value of type Set.
new Set(iterable)Parameters
| Parameter | Optional/Required | Description |
|---|---|---|
iterable | optional | An iterable object whose elements will be added to the new Set. If the iterable contains duplicate elements, only the first occurrence will be added. |
This constructor creates a Set object containing the unique elements from the given iterable.
Returns value of type Set.
✐ Examples
1 Creating an empty Set
In JavaScript, you can create an empty Set object using the Set constructor with no arguments.
For example,
- Call the
Setconstructor without any arguments. - The result is stored in the variable
mySet. - We log
mySetto the console using theconsole.log()method.
JavaScript Program
const mySet = new Set();
console.log(mySet);Output
Set(0) {}2 Creating a Set from an array
In JavaScript, you can create a Set object from an array using the Set constructor. The Set will only contain unique elements from the array.
For example,
- Define an array
arrwith some elements, including duplicates. - Call the
Setconstructor witharras an argument. - The result is stored in the variable
mySet. - We log
mySetto the console using theconsole.log()method.
JavaScript Program
const arr = [1, 2, 2, 3, 4, 4, 5];
const mySet = new Set(arr);
console.log(mySet);Output
Set(5) { 1, 2, 3, 4, 5 }3 Creating a Set from a string
In JavaScript, you can create a Set object from a string using the Set constructor. Each character in the string will be a unique element in the Set.
For example,
- Define a string
strwith some characters, including duplicates. - Call the
Setconstructor withstras an argument. - The result is stored in the variable
mySet. - We log
mySetto the console using theconsole.log()method.
JavaScript Program
const str = 'hello';
const mySet = new Set(str);
console.log(mySet);Output
Set(4) { 'h', 'e', 'l', 'o' }Summary
In this JavaScript tutorial, we learned about Set constructor of Set: the syntax and few working examples with output and detailed explanation for each example.