A set stores distinct values, so adding an item that is already present has no effect. ES6’s built-in Set replaces a fragile workaround that mimicked sets with objects. section 9.3 section 9.3.1
Use a Set to:
- Create an empty set or initialize one from an array. section 9.3.1
- Check membership with has, add unique items with add, and read the item count from size. section 9.3.1
- Iterate with for...of; values are visited in insertion order. section 9.3.1
Duplicate names stay out
Initialize a set with “Kuma,” “Hattori,” “Yagyu,” and “Hattori” again: its size is three. Add “Yoshi” to increase the size; adding “Kuma” again leaves it unchanged. section 9.3.1
Listing 9.20. Creating a set
const ninjas = new Set(["Kuma", "Hattori", "Yagyu", "Hattori"]); #A
assert(ninjas.has("Hattori"), "Hattori is in our set"); #B
assert(ninjas.size === 3, "There are only three ninjas in our set!"); #B
assert(!ninjas.has("Yoshi"), "Yoshi is not in, yet.."); #C
ninjas.add("Yoshi"); #C
assert(ninjas.has("Yoshi"), "Yoshi is added"); #C
assert(ninjas.size === 4, "There are four ninjas in our set!"); #C
assert(ninjas.has("Kuma"), "Kuma is already added"); #D
ninjas.add("Kuma"); #D
assert(ninjas.size === 4, "Adding Kuma again has no effect"); #D
for(let ninja of ninjas) { #E
assert(ninja !== null, ninja); #E
} #E
See the complete example of creating a set, checking membership, adding values, checking size, and iterating. section 9.3.1














