JavaScript Sets

A JavaScript Set is a collection of unique values.

Each value can only occur once in a Set.

A Set can hold any value of any data type.

Set Methods

Method Description
new Set() Creates a new Set
add() Adds a new element to the Set
delete() Removes an element from a Set
has() Returns true if a value exists
clear() Removes all elements from a Set
forEach() Invokes a callback for each element
values() Returns an Iterator with all the values in a Set
keys() Same as values()
entries() Returns an Iterator with the [value,value] pairs from a Set
Property Description
size Returns the number elements in a Set

How to Create a Set

You can create a JavaScript Set by:

  • Passing an Array to new Set()
  • Create a new Set and use add() to add values
  • Create a new Set and use add() to add variables

The new Set() Method

Pass an Array to the new Set() constructor:

Example

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

Create a Set and add literal values:

Example

// Create a Set
const letters = new Set();

// Add Values to the Set
letters.add("a");
letters.add("b");
letters.add("c");

Create a Set and add variables:

Example

// Create Variables
const a = "a";
const b = "b";
const c = "c";

// Create a Set
const letters = new Set();

// Add Variables to the Set
letters.add(a);
letters.add(b);
letters.add(c);

The add() Method

Example

letters.add("d");
letters.add("e");

If you add equal elements, only the first will be saved:

Example

letters.add("a");
letters.add("b");
letters.add("c");
letters.add("c");
letters.add("c");
letters.add("c");
letters.add("c");
letters.add("c");