JavaScript Set

JavaScript Set is a collection of unique values.

Each value can only appear once in the Set.

Values can be any type, primitive or object.

How to create Set

You can create a JavaScript Set in the following ways:

  1. Pass an array to new Set().
  2. Create an empty Set and use add() Add values.

new Set() method

Pass an array to new Set() Constructor:

Instance

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

Try It Yourself

Create Set and add values:

Instance

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

Try It Yourself

Create Set and add variables:

Instance

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

Try It Yourself

add() method

Instance

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

Try It Yourself

If the same element is added, only the first one will be saved:

Instance

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

Try It Yourself

List elements

You can use for..of Loop through all Set elements (values):

Instance

// 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

Set is an object

typeof Returns object:

typeof letters;      // Returns object

Try It Yourself

instanceof Set Returns true:

letters instanceof Set;  // Returns true

Try It Yourself

Complete Set Reference Manual

For a complete reference, please visit our:JavaScript Set Reference Manual.

This manual includes descriptions and examples of all Set properties and methods.

Browser Support

Set is ES6 Features(JavaScript 2015).

Starting from June 2017, all modern browsers support ES6:

Chrome Edge Firefox Safari Opera
Chrome 51 Edge 15 Firefox 54 Safari 10 Opera 38
May 2016 April 2017 June 2017 September 2016 June 2016

Internet Explorer does not support Set.