JavaScript Set Complete Tutorial

In this section, we will learn what the Set object is and how to use it in JavaScript.

What is Set in JavaScript?

The `Set` is a collection of unique elements. That is the set cannot contain duplicate elements. Basically, if we attempt to add a value that is already in the collection, the execution engine ignores it and won’t add it to the collection.

How to Create Set in JavaScript?

We use the `Set` constructor method to create a `Set` collection object.

Example:

const collect = new Set();

The `Set` constructor function has multiple useful methods that can be used to add and remove elements and other types of operations. These methods are explained in the next couple of sections.

For example, the `add()` method adds an element to the target Set-object. Or the `delete()` element removes one element from the target set-object.

Example: creating Set in JavaScript

const collect = new Set();
collect.add("Jack");
collect.add("Jack");
collect.add("Omid");
collect.add("John");

if (collect.has("Omid")){
  collect.delete("Omid");
}
for(const value of collect.values()){
  console.log(value);
}

Output:

John

Jack

Note that here we’ve added the value `Jack` two times, but for the second time the execution engine ignored the assignment because the value is already in the collection.

In the next couple of sections, you’ll see how the methods that we’ve used in this program works.

JavaScript Set Methods

Method Name

Description

size

This property is used to get the current number of elements in the target Set object.

add()

This method is used to add a new value to a set object.

has()

This method is used to see if the target Set object has a specific value or not.

clear()

This method is used to clear the entire values of the target Set object.

delete()

This method is used to delete a specific value from the target Set object.

values()

This method is used to return the entire values of the target Set object.

entries()

This method is used to return the entire entries of the target Set object.

forEach()

This method is used to run a block of instructions on every element in the target Set object.

Leave a Reply