Sub topic 1
A Quick Refresher on Set
The new composition methods (union, intersection, difference, and the rest) all build on three behaviours that Set has always had. A Set stores only unique values. It decides uniqueness with an algorithm called SameValueZero. It remembers the order in which values were inserted. This chapter reviews those three rules, because every later chapter depends on them.
Prerequisites
This chapter assumes you are comfortable with:
- JavaScript variables, functions, and arrow functions
- Creating a Set and using
add,has,delete, andfor...of - Spread syntax (
[...iterable]) and Array methods such asfilter - The difference between primitive values and object references
You only need a runtime that supports Set. Any modern browser or Node.js version works for this chapter.
Uniqueness: One Copy of Each Value
A Set holds each value at most once. Adding a value that is already present does nothing, and add returns the Set either way, so calls can be chained.
const langs = new Set();
langs.add("js").add("css").add("js");
console.log(langs.size); // 2
console.log(langs.has("css")); // true
console.log(langs.delete("css")); // true (it was present)
console.log(langs.delete("css")); // false (already gone)The constructor accepts any iterable, so the quickest way to remove duplicates from an array is to pass it straight in:
const ids = [3, 1, 3, 2, 1];
const unique = [...new Set(ids)];
console.log(unique); // [3, 1, 2]A common slip is passing a string where you meant an array. Strings are iterable, so new Set("hello") gives you a Set of the characters "h", "e", "l", "o", not a Set holding the single word.
SameValueZero: How Sets Compare Values
A Set decides whether two values are the same using SameValueZero. It works almost exactly like ===, with one exception: NaN counts as equal to itself. Like ===, it treats +0 and -0 as the same value.
| Comparison | `===` | SameValueZero |
|---|---|---|
| `1` vs `"1"` | false | false |
| `NaN` vs `NaN` | false | true |
| `+0` vs `-0` | true | true |
| `{}` vs `{}` | false | false |
const s = new Set([NaN, NaN, 0, -0, 1, "1"]);
console.log(s.size); // 4 (NaN, 0, 1, "1")
console.log(s.has(NaN)); // trueThe last row of the table matters most in practice. Objects are compared by reference, not by their contents. Two object literals with identical properties are two different elements. A later chapter shows how this affects intersection and the other methods. For now, remember that a Set never looks inside an object.
const s = new Set([{ id: 1 }, { id: 1 }]);
console.log(s.size); // 2Insertion Order
A Set iterates its values in the order they were first added. Adding an existing value again does not move it. Deleting a value and then adding it back places 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 at the end
console.log([...order]); // ["b", "c", "a"]
for (const value of order) {
console.log(value); // b, then c, then a
}This ordering is guaranteed by the language specification, not an implementation detail. The new Set methods rely on it when they decide the order of their results.
Common Errors
- Expecting deep equality.
new Set([[1], [1]]).sizeis2, because the two arrays are different references. - Assuming
addreorders. Re-adding a value leaves its position alone. Delete it first if you want it at the end. - Mixing types.
1and"1"are different elements. Values read from form fields or URLs are strings, so normalize them before adding. - Passing a string to the constructor.
new Set("abc")splits the string into characters. Usenew Set(["abc"])to store the whole string.
Exercise
What does this log, and why? const s = new Set([2, NaN, "2", 2, NaN]); s.delete(2); s.add(2); console.log([...s]);
Show answer
It logs [NaN, "2", 2]. The constructor keeps one 2 and one NaN, because SameValueZero treats NaN as equal to itself, and "2" is a separate string element, giving [2, NaN, "2"]. Deleting 2 and adding it back moves it to the end.
Exercise
A teammate writes new Set([{ role: "admin" }]).has({ role: "admin" }) and expects true. What is the actual result, and how could they fix the check?
Show answer
The result is false, because the object passed to has is a different reference from the one stored in the Set. They should keep a reference to the original object and pass that reference to has, or store a primitive key such as the string "admin" instead of an object.