A JavaScript Set is a collection that holds unique values, where each value can appear only once. These values can be of any type, including primitive values or objects.
You can create a JavaScript Set by:
new Set()
add()
to include values.Pass an array to the new Set() constructor to create a Set:
// Create a Set const letters = new Set([“a”,“b”,“c”]); |
Create a Set and include values:
// 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 include variables:
// Create a Set const letters = new Set(); // Create Variables const a = “a”; const b = “b”; const c = “c”; // Add Variables to the Set letters.add(a); letters.add(b); letters.add(c); |
letters.add(“d”); letters.add(“e”); |
If you add duplicate elements, only the first instance will be retained.
letters.add(“a”); letters.add(“b”); letters.add(“c”); letters.add(“c”); letters.add(“c”); letters.add(“c”); letters.add(“c”); letters.add(“c”); |
You can display all Set elements (values) using a for…of loop.
// Create a Set const letters = new Set([“a”,“b”,“c”]); // List all Elements let text = “”; for (const x of letters) { text += x; } |
typeof
returns “object.”
typeof letters; // Returns object |
instanceof Set returns true.
letters instanceof Set; // Returns true |
Set is an ES6 feature (introduced in JavaScript 2015).
All modern browsers have fully supported ES6 since June 2017.
Set is not supported in Internet Explorer.