JavaScript Set
- Previous Page JS Iterable Objects
- Next Page JS Set Methods
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:
- Pass an array to
new Set()
. - 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"]);
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");
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);
add() method
Instance
letters.add("d"); letters.add("e");
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");
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; }
Set is an object
typeof
Returns object:
typeof letters; // Returns object
instanceof Set
Returns true:
letters instanceof Set; // Returns true
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.
- Previous Page JS Iterable Objects
- Next Page JS Set Methods