A Set stores distinct items: adding an item already present has no effect. It is like a Map with keys but no values, useful when membership matters more than associating items with data. section 10.3 section 10.3.1
Create a Set from an iterable such as an array, then use its membership and size APIs:
- The constructor ignores duplicate items; add(item) also leaves an existing item unchanged. section 10.3.1
- Use has(item) to test membership and size to count items. For repeated membership checks on an array, Set has is described as faster than includes. section 10.3.1
- Uniqueness for objects and functions depends on reference identity: the same function reference is stored once, while separate function expressions are distinct. section 5.3.1
Listing 10.13 Creating a set
const ninjas = new Set([ #A
"Kuma", #A
"Hattori", #A
"Yagyu", #A
"Hattori", #A
]); #A
console.assert( #B
ninjas.has("Hattori"), #B
"Hattori is in our set", #B
); #B
console.assert( #C
ninjas.size === 3, #C
"There are only three ninjas in our set!", #C
); #C
ninjas.add("Yoshi"); #D
console.assert(ninjas.has("Yoshi"), "Yoshi is added"); #D
console.assert(
ninjas.size === 4,
"There are four ninjas in our set!",
);
console.assert(ninjas.has("Kuma"), "Kuma is already added");
ninjas.add("Kuma");
console.assert(
ninjas.size === 4,
"Adding Kuma again has no effect",
);
for (let ninja of ninjas) { #E
console.assert(ninja !== null, ninja); #E
} #E
The duplicate "Hattori" is discarded during construction, and adding "Kuma" again leaves the set size unchanged. section 10.3.1
Listing 5.5 Storing a collection of unique functions
let count = 0;
const increment = () => {
count++;
};
const funcSet = new Set(); #A
funcSet.add(increment); #B
funcSet.add(increment); #B
funcSet.forEach((func) => func()); #C
console.assert(count === 1, #D
"The function was only added to the set once"); #D
Adding the same callback reference twice results in one stored function and one invocation. section 5.3.1
Sets also support combinations: union collects items from either set, intersection keeps shared items, difference keeps items unique to one set, and isSubsetOf tests containment. section 10.3.2
const ninjas = new Set(["Kuma", "Hattori", "Yagyu"]);
const samurai = new Set(["Hattori", "Oda", "Tomoe"]);
const ninjaSamurais = ninjas.intersection(samurai);
console.assert(
ninjaSamurais.size === 1,
"There's only one ninja samurai",
);
console.assert(
ninjaSamurais.has("Hattori"),
"Hattori is his name",
);
Intersecting the ninja and samurai sets produces the shared item, Hattori. section 10.3.2


















