JavaScript Sets
How to Create a Set
You can create a JavaScript Set by either:
- Passing an array to the new Set() constructor
- Creating an empty set and using the add() method to add values
The new Set() Method
You can pass an array to the new Set() constructor to create a set:
Example
// Create a Setconst fruits = new Set(["apple", "banana", "cherry"]);
You can also create a set and then add values to it:
Example
// Create a Setconst fruits = new Set();// Add Values to the Setfruits.add("apple");fruits.add("banana");fruits.add("cherry");
Create a Set and Add Variables
You can create a set and add variables to it:
Example
// Create a Setconst fruits = new Set();// Create Variablesconst apple = "apple";const banana = "banana";const cherry = "cherry";// Add Variables to the Setfruits.add(apple);fruits.add(banana);fruits.add(cherry);
The add() Method
You can use the add() method to add values to a set:
Example
fruits.add("date");fruits.add("elderberry");
If you add duplicate elements, only the first occurrence will be kept:
Example
fruits.add("apple");fruits.add("banana");fruits.add("cherry");fruits.add("cherry");fruits.add("cherry");
Listing the Elements
You can list all the elements in a set using a for..of loop:
Example
// Create a Setconst fruits = new Set(["apple", "banana", "cherry"]);// List all Elementslet text = "";for (const fruit of fruits) { text += fruit + " ";}
Sets are Objects
The typeof operator returns "object" for sets:
typeof fruits; // Returns "object"
The instanceof operator returns true when checking if an object is an instance of Set:
fruits instanceof Set; // Returns true
Complete Set Reference
For a complete reference, visit the Complete JavaScript Set Reference. The reference contains descriptions and examples of all Set properties and methods.
Browser Support
Set is an ES6 feature (JavaScript 2015).
ES6 is fully supported in all modern browsers since June 2017:
Browser
Version
Chrome
51 (May 2016)
Edge
15 (Apr 2017)
Firefox
54 (Jun 2017)
Safari
10 (Sep 2016)
Opera
38 (Jun 2016)
Set is not supported in Internet Explorer.