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:

1.
new Set()

This constructor creates an empty Set object.

Returns value of type Set.

2.
new Set(iterable)

Parameters

ParameterOptional/RequiredDescription
iterableoptionalAn 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,

  1. Call the Set constructor without any arguments.
  2. The result is stored in the variable mySet.
  3. We log mySet to the console using the console.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,

  1. Define an array arr with some elements, including duplicates.
  2. Call the Set constructor with arr as an argument.
  3. The result is stored in the variable mySet.
  4. We log mySet to the console using the console.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,

  1. Define a string str with some characters, including duplicates.
  2. Call the Set constructor with str as an argument.
  3. The result is stored in the variable mySet.
  4. We log mySet to the console using the console.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.