Sub topic 3
Set Fundamentals
This chapter assumes you know JavaScript variables and functions, arrays, for...of loops, and the difference between primitive values and object references. It also builds on the Map chapter, because a Set uses a very similar API.
What a Set Is
A Set is a collection of unique values. Each value appears at most once, no matter how many times you add it. A Map stores key/value pairs. A Set stores only values, and you can think of each value as its own key.
Use a Set when the main question you ask is "have I seen this value?" Arrays can answer that question too, but array.includes() checks every element in turn. Engines implement set.has() with hash tables or similar structures, so lookups stay fast as the collection grows.
Creating a Set
Call the constructor with no arguments for an empty Set, or pass any iterable to fill it. Duplicates in the iterable are dropped.
const empty = new Set();
const ids = new Set([101, 102, 101, 103]);
const letters = new Set('hello');
console.log(empty.size); // 0
console.log(ids.size); // 3
console.log(letters); // Set(4) { 'h', 'e', 'l', 'o' }A string is iterable one character at a time, so new Set('hello') holds characters, not one string. To store the whole string, wrap it in an array: new Set(['hello']).
The Core Methods
| Method | Returns | Effect |
|---|---|---|
| `add(value)` | The Set itself | Adds `value` if it is not already present |
| `has(value)` | `true` or `false` | Reports whether `value` is present |
| `delete(value)` | `true` if removed, else `false` | Removes `value` |
| `clear()` | `undefined` | Removes every value |
| `size` (property) | A number | The count of values |
const online = new Set();
online.add('ana').add('ben').add('ana');
console.log(online.size); // 2
console.log(online.has('ben')); // true
console.log(online.delete('ben')); // true
console.log(online.delete('zoe')); // false
online.clear();
console.log(online.size); // 0add returns the Set, so calls can be chained, just like Map.prototype.set. Adding a value that is already present does nothing and throws no error.
Objects in a Set
Primitives such as numbers and strings are compared by value. Objects are compared by reference, so two objects that look the same are still two entries.
const seen = new Set();
const a = { id: 1 };
seen.add(a);
seen.add({ id: 1 });
console.log(seen.size); // 2
console.log(seen.has(a)); // true
console.log(seen.has({ id: 1 })); // falseThe exact equality rule, including how NaN and -0 behave, is covered in the chapter on SameValueZero. A Set also remembers the order in which values were first added. The chapter on iterating Sets explains how to use that order.
Common Errors
- Calling
set.length. Sets havesize, andlengthisundefined. - Reading values with brackets, as in
set[0]. Sets have no index access. Usehas, or iterate. - Passing several arguments to the constructor, as in
new Set(1, 2, 3). The constructor reads only its first argument, and a number is not iterable, so this throws aTypeError. Pass an array instead.
Exercise
After running const s = new Set([1, 2]); s.add(2).add('2'); s.delete(1);, what is s.size, and what does s.has(2) return?
Show answer
s.size is 2 and s.has(2) returns true. The Set starts as {1, 2}. Adding 2 again changes nothing, adding the string '2' creates a separate entry because strings and numbers are different values, and deleting 1 leaves {2, '2'}.
Exercise
Why does new Set([[1, 2], [1, 2]]).size equal 2 instead of 1?
Show answer
Each array literal creates a new object, and a Set compares objects by reference. The two arrays have the same contents but are different objects, so both are stored.