JavaScript Set Reference Manual

JavaScript Set (Set) is a collection of unique values.

Each value in the set can only appear once.

These values can be of any type, including primitive values or objects.

How to Create a Set

You can create a JavaScript set in the following ways:

  • Pass an array to new Set()
  • Create a set and use add() Method to add values

Example 1

Pass an array to new Set() Constructor:

// Create a set
const letters = new Set(["a","b","c"]);

Try It Yourself

Example 2

Create a set and add values:

// Create a set
const letters = new Set();
// Add values to the set
letters.add("a");
letters.add("b");
letters.add("c");

Try It Yourself

JavaScript Set Methods and Properties

Method/Property Description
new Set() Create a new set.
add() Add a new element to the set.
clear() Remove all elements from the set.
delete() Remove an element from the set.
entries() Returns an iterator containing pairs [value, value] (each element in the set is both a key and a value).
forEach() Call a callback function for each element.
has() Returns true if the set contains a certain value.
keys() Same as the values() method.
size Returns the number of elements in the set.
values() Returns an iterator containing the values in the set.

new Set() method

Pass an array to new Set() Constructor:

Example

// Create a set
const letters = new Set(["a","b","c"]);

Try It Yourself

List set elements

You can use for..of Loop through all elements (values) in the set:

Example

// Create a set
const letters = new Set(["a","b","c"]);
// List all elements
let text = "";
for (const x of letters) {
  text += x;
}

Try It Yourself