Sub topic 1
A Quick Refresher on Set
Prerequisites
This chapter assumes you already know:
- JavaScript variables, functions, and arrow functions
- How to create and iterate a
Setwithadd,has,delete, andfor...of - Spread syntax and Array methods such as
filter - The difference between object references and primitive values
A Quick Refresher on Set
A Set stores unique values. It compares values with SameValueZero, which works like === with two differences: NaN equals NaN, and +0 equals -0. A Set iterates in insertion order. If you add a value that is already present, the Set ignores it and the value keeps its original position.
const s = new Set([3, 1, 3, NaN, NaN]);
console.log([...s]); // [3, 1, NaN]
console.log(s.size); // 3New Sets In, Originals Untouched
ES2025 added composition methods to Set.prototype. Each one takes another set as its argument and returns a brand-new Set. Neither the receiver (the set you call the method on) nor the argument is modified. This means you can chain calls and reuse the original sets without making defensive copies first.
Combining Sets with union
union returns every element that appears in either set. The receiver's elements come first in their original order. After them come any elements of the argument that were not already present.
const frontend = new Set(["js", "css", "html"]);
const backend = new Set(["js", "sql"]);
const all = frontend.union(backend);
console.log([...all]); // ["js", "css", "html", "sql"]
console.log(frontend.size); // 3 (unchanged)The duplicate "js" appears only once, at the position it had in frontend.
Finding Common Elements with intersection
intersection keeps only the elements found in both sets.
const a = new Set([1, 2, 3, 4]);
const b = new Set([3, 4, 5]);
console.log(a.intersection(b).size); // 2 (contains 3 and 4)
console.log(a.size, b.size); // 4 3 (both unchanged)A common mistake is to pass an array, as in a.intersection([3, 4]). That call throws a TypeError because the argument must be set-like. Wrap the array first with new Set(array).
Exercise
Given const x = new Set(["b", "a"]) and const y = new Set(["c", "a"]), what does [...x.union(y)] print, and what is x.size afterward?
Show answer
["b", "a", "c"]. The receiver's elements come first in insertion order, then the new element "c" from y. x.size is still 2 because union returns a new Set.
Exercise
Why does new Set([1, 2]).intersection([2]) throw instead of returning a Set containing 2?
Show answer
An array is not set-like. It has no size property or has method, so the method throws a TypeError. Use new Set([1, 2]).intersection(new Set([2])) instead.