JavaScript Sets


A JavaScript Set is a group of distinct values.

Every number or item can only be in a set once.

A set can store values of various data types.

Set Methods

MethodDescription
new Set()Generates a fresh Set.
add()Inserts a fresh item into the Set.
delete()Deletes an item from a Set.
has()Indicates whether a value is present.
clear()Clears all items from a Set.
forEach()Triggers a function for every element.
values()Produces an Iterator containing all the values from a Set.
keys()Similar to the values() method.
entries()Generates an Iterator containing pairs of [value, value] retrieved from a Set.
PropertyDescription
sizeShows how many items are in a Set.

How to Create a Set

You can make a JavaScript Set by:

  • Sending a list to the new Set() method.
  • Make a fresh set and employ the add() function to include values.
  • Generate a fresh set and employ the add() method to include variables.

The new Set() Method

Send an array to the new Set() constructor.

Make a collection and include specific values:

Make a collection and include variables:


The add() Method

If you include identical elements, only the initial one will be retained:


The forEach() Method

The forEach() method calls a function for every element in a Set.


The values() Method

The values() method gives back an Iterator object that has all the values present in a Set.

You can now utilize the Iterator object to reach the elements.


The keys() Method

A set doesn't have any keys.

The function keys() gives the same result as values().

This allows Sets to work well with Maps.


The entries() Method

A set does not have any keys.

The function entries() gives back pairs like [value, value], not like [key, value].

This allows Sets to work well with Maps:


Sets are Objects