Sub topic 1
A Quick Refresher on Set
ES2025 added composition methods such as union, intersection, and difference to Set. They build on a few rules that Set has followed since ES2015: how it decides two values are the same, how it orders its elements, and how it behaves when you iterate over it. If you can predict those rules, you can predict what each new method returns. This chapter reviews them, with emphasis on the details that matter later.
Prerequisites
This chapter assumes you already know:
- JavaScript variables, functions, and arrow functions.
- How to create a
Setand useadd,has,delete, andfor...ofon it, at least at a basic level. - Spread syntax (
[...iterable]) and Array methods such asfilter. - The difference between primitive values (numbers, strings, booleans) and object references.
The goal is to make your mental model precise. Edge cases such as NaN, -0, and re-inserting an element come up again in later chapters.
What a Set Is
A Set is a collection of unique values. A value is either in the set or not in it. A set never holds two copies of the same value, and it keeps no count of how many times you added something.
Unlike an array, a set has no numeric indexes. You can't write set[0]. Its main job is to answer one question quickly: "is this value in the collection?" In every major engine, has runs in roughly constant time on average. array.includes has to scan the whole array.
const ids = [101, 205, 101, 333, 205];
const uniqueIds = new Set(ids);
console.log(uniqueIds.size); // 3
console.log(uniqueIds.has(205)); // true
console.log(uniqueIds.has(999)); // false
console.log(uniqueIds[0]); // undefined (no index access)The Core API
These are the instance members you will use alongside the new methods:
| Member | Returns | Notes |
|---|---|---|
| `new Set(iterable)` | a new Set | Accepts any iterable, or nothing |
| `add(value)` | the same Set | You can chain calls |
| `has(value)` | boolean | Membership test |
| `delete(value)` | boolean | `true` if the value was present |
| `clear()` | `undefined` | Removes every element |
| `size` | number | A getter property, not a method |
| `keys()`, `values()` | iterator | Both yield the elements |
| `entries()` | iterator | Yields `[value, value]` pairs |
| `forEach(fn)` | `undefined` | Calls `fn(value, value, set)` |
The add method returns the set itself, so calls can be chained:
const roles = new Set().add("viewer").add("editor").add("viewer");
console.log(roles.size); // 2
console.log(roles.delete("editor")); // true
console.log(roles.delete("editor")); // false (already gone)Every method in this table except has and the iterators changes the set in place. The ES2025 composition methods work differently: they return a brand-new set. That difference is the subject of the next chapter.
The keys, values, and entries names, and the odd (value, value, set) callback signature for forEach, exist so that Set and Map share an interface. A set behaves like a map whose keys and values are the same thing. Keep this in mind, because the new methods read their argument through size, has, and keys. That lets them accept a Map as an argument, which a later chapter covers.
Uniqueness and SameValueZero
To decide whether a value is already present, a Set uses an algorithm called SameValueZero. It is almost the same as strict equality (===), with one difference: NaN counts as equal to NaN.
| Comparison | `===` | `Object.is` | SameValueZero (Set) |
|---|---|---|---|
| `NaN` vs `NaN` | false | true | true |
| `0` vs `-0` | true | false | true |
| `1` vs `"1"` | false | false | false |
| `{}` vs `{}` | false | false | false |
| same object reference | true | true | true |
Each row has practical consequences:
const s = new Set([NaN, NaN, 0, -0, 1, "1"]);
console.log(s.size); // 4: NaN, 0, 1, "1"
console.log(s.has(NaN)); // true, even though NaN !== NaN
console.log(s.has(-0)); // true
console.log(s.has("1")); // true
console.log(s.has(1)); // true, and a different element from "1"
const [first, second] = s;
console.log(Object.is(second, -0)); // false: stored as +0The last line shows a less obvious detail. When you add -0, the set stores it as +0, so you never get -0 back out of a set.
Objects compare by reference
For objects, arrays, and functions, SameValueZero compares references. Two objects with identical contents are different elements:
const user = { id: 1 };
const people = new Set([user, { id: 1 }]);
console.log(people.size); // 2
console.log(people.has(user)); // true
console.log(people.has({ id: 1 })); // false: a new, different objectThis rule carries straight into the new methods. A later chapter, "Objects in Sets: Reference Equality," covers what it means for intersection and difference and how to work around it.
Insertion Order
Sets are ordered. Iteration visits elements in the order they were first inserted. Two rules follow from this, and both affect the result order of the new methods:
- Adding a value that is already present does nothing. The value does not move.
- Deleting a value and then adding it again puts it at the end.
const order = new Set(["a", "b", "c"]);
order.add("a"); // already present, position unchanged
console.log([...order]); // ["a", "b", "c"]
order.delete("a");
order.add("a"); // re-inserted, goes to the end
console.log([...order]); // ["b", "c", "a"]Note that insertion order is not sorted order. new Set([3, 1, 2]) iterates as 3, 1, 2. If you need sorted output, convert to an array and sort it: [...set].sort((x, y) => x - y).
Iterating a Set
A set is iterable, so it works anywhere an iterable is accepted: for...of, spread, destructuring, Array.from, and the Set constructor itself.
const langs = new Set(["js", "css", "html"]);
for (const lang of langs) {
console.log(lang); // js, css, html
}
langs.forEach((value, key, set) => {
console.log(value === key, set === langs); // true true
});
console.log([...langs.entries()]); // [["js","js"], ["css","css"], ["html","html"]]
console.log(Array.from(langs, (l) => l.toUpperCase())); // ["JS", "CSS", "HTML"]Changing a set while you iterate
Set iteration is live. If you change a set during a for...of loop:
- Elements added during the loop are visited later in the same loop.
- Elements deleted before the loop reaches them are skipped.
const live = new Set([1, 2, 3]);
for (const n of live) {
if (n === 1) live.delete(2); // 2 is never visited
if (n === 3) live.add(4); // 4 is visited
console.log(n); // 1, 3, 4
}If you add a new element on every pass, the loop never ends. When you need to change a set based on its own contents, iterate over a copy: for (const n of [...live]). You can also build a separate result set, which is what the new composition methods do for you.
Converting Between Arrays and Sets
Most real data arrives as arrays, so you will convert back and forth all the time:
const tags = ["js", "web", "js", "css", "web"];
const tagSet = new Set(tags); // array to Set (removes duplicates)
const uniqueTags = [...tagSet]; // Set to array
const sameAgain = Array.from(tagSet); // also Set to array
console.log(uniqueTags); // ["js", "web", "css"]
console.log(sameAgain.length); // 3The one-liner [...new Set(array)] is the standard way to remove duplicates from an array while keeping the first occurrence of each value in its original position.
Before ES2025, combining sets meant going through arrays like this. For example, you would compute a union with new Set([...a, ...b]). The chapter on browser support comes back to these patterns as fallbacks for older runtimes.
Common Mistakes
These errors come up often, and several of them show up again with the new methods.
Passing a string to the constructor. A string is iterable, so the set gets one element per character:
console.log([...new Set("hello")]); // ["h", "e", "l", "o"]
console.log([...new Set(["hello"])]); // ["hello"]Passing separate arguments. The constructor takes one iterable. It does not take a list of values:
try {
new Set(1, 2, 3);
} catch (err) {
console.log(err instanceof TypeError); // true: 1 is not iterable
}Calling size as a method or looking for length. set.size() throws a TypeError because size is a number, and set.length is undefined.
Expecting JSON serialization. JSON.stringify(new Set([1, 2])) produces "{}". Convert to an array first: JSON.stringify([...set]).
Treating arrays as sets. An array is iterable, but it has no size property and no has method. The constructor accepts arrays without complaint. The ES2025 methods do not, and passing an array to union throws a TypeError. A later chapter explains why.
Why These Rules Matter Next
Each ES2025 method applies the rules from this chapter:
- SameValueZero decides which elements
intersectiontreats as shared and which onesdifferenceremoves. - Insertion order determines the order of elements in every result set.
- Reference equality explains why two lists of look-alike objects can have an empty intersection.
- The
size/has/keysinterface is what the new methods require from their argument.
The next chapter covers the most important difference between the old API and the new one: the composition methods never change the sets you call them on.
Exercise
What does this code print, and why? const s = new Set([NaN, 0, "0", -0, NaN]); console.log(s.size, [...s]);
Show answer
It prints 3 [NaN, 0, "0"]. SameValueZero treats NaN as equal to NaN, so the second NaN is ignored. 0 and -0 are also equal under SameValueZero, so -0 is not added again. The string "0" is a different type from the number 0 and is never coerced, so it stays as a separate element.
Exercise
Starting from const s = new Set(["x", "y", "z"]), you run s.add("y"); s.delete("x"); s.add("x"); s.add("w"). What is the result of [...s]?
Show answer
["y", "z", "x", "w"]. Adding "y" again does nothing because it is already present. Deleting "x" and then adding it moves it to the end. Then "w" is appended after it.
Exercise
A developer writes const allowed = new Set(userIds) where userIds comes from a database as numbers, then checks allowed.has(req.params.id) where the ID comes from the URL. The check always returns false. What is wrong, and how do you fix it?
Show answer
URL parameters are strings, and Set never coerces types, so the string "42" does not match the number 42. Normalize one side before checking, for example allowed.has(Number(req.params.id)), or build the set from strings with new Set(userIds.map(String)).
Exercise
Write code that removes duplicate values from the array [3, 1, 3, 2, 1] and returns the unique values sorted in ascending order.
Show answer
const result = [...new Set([3, 1, 3, 2, 1])].sort((a, b) => a - b); gives [1, 2, 3]. The Set removes duplicates and keeps first-insertion order (3, 1, 2). Sorting is a separate step, because a Set's order is insertion order, not sorted order.