Loading lesson path
Concept visual
Start at both ends
A JavaScript Set is a collection of unique values. Each value can only occur once in a Set. The values can be of any type, primitive values or objects.
You can create a JavaScript Set by:
to add values
constructor:
// Create a Set const letters = new Set(["a","b","c"]);Create a Set and add 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 add 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);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");You can list all Set elements (values) with 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;
}Sets are Objects typeof returns object:
typeof letters; // Returns object instanceof Set returns true:
letters instanceof Set; // Returns trueES6 feature. ES6 is fully supported in all modern browsers since June 2017:
51
15
54
10