Sub topic 3
Set Fundamentals
A Set is a built-in collection that stores unique values. Each value appears in it at most once. You can add values, check whether a value is present, remove values, and read how many values it holds. A Set has no keys and no indexes. The value is the only thing it stores.
This chapter assumes you know JavaScript variables and functions, arrays and objects, for...of loops, the spread operator, and the difference between primitive values and object references. It covers how to create a Set and how its core methods behave, including what they return and the mistakes people make with them most often. The exact equality rule a Set uses, ways to iterate one, and operations that combine two sets each get their own chapter later.
What a Set Is For
Use a Set when the question you need to answer is "have I got this value?" rather than "where is this value?" or "what value goes with this key?" Typical cases include:
- Tracking which user IDs have already been processed.
- Collecting the distinct tags that appear across many posts.
- Recording which feature flags are switched on.
- Checking membership quickly inside a loop.
You could do all of these with an array and includes, but that has two costs. An array lets duplicates in unless you check before every push. Also, includes scans the array from the start, so lookups get slower as the array grows. The specification requires Set lookups to be sublinear on average, and engines implement them as hash tables, so has takes about the same time whether the set holds ten values or ten million.
| Need | Array | Set |
|---|---|---|
| Keep duplicates | Yes | No, duplicates are ignored |
| Access by position | `arr[0]` | Not supported |
| Membership check | `includes`, linear scan | `has`, near constant time |
| Count | `length` | `size` |
| Remove a specific value | `splice` after `indexOf` | `delete(value)` |
Creating a Set
Call the Set constructor with new. With no argument you get an empty set. If you pass an iterable, such as an array, every value it yields is added in order, and repeated values are skipped.
const empty = new Set();
console.log(empty.size); // 0
const primes = new Set([2, 3, 5, 7, 3, 2]);
console.log(primes.size); // 4
console.log(primes); // Set(4) { 2, 3, 5, 7 }
const mixed = new Set([1, '1', true, null, undefined]);
console.log(mixed.size); // 5The number 1 and the string '1' are different values, so mixed keeps both. A Set never converts types when it compares values.
The constructor accepts any iterable, including another Set. Copying a set this way gives you an independent shallow copy:
const original = new Set(['a', 'b']);
const copy = new Set(original);
copy.add('c');
console.log(original.size); // 2
console.log(copy.size); // 3Constructor Pitfalls
Three mistakes with the constructor come up often enough to learn ahead of time.
// 1. A string is iterable, so it is split into characters.
const letters = new Set('hello');
console.log(letters.size); // 4 -> 'h', 'e', 'l', 'o'
// To store the whole word, wrap it in an array.
const words = new Set(['hello']);
console.log(words.size); // 1
// 2. Separate arguments are not values to add.
try {
new Set(1, 2, 3);
} catch (err) {
console.log(err instanceof TypeError); // true: 1 is not iterable
}
// 3. Calling Set without new throws.
try {
Set([1, 2]);
} catch (err) {
console.log(err instanceof TypeError); // true
}Passing undefined or null is allowed and gives an empty set, so new Set(maybeArray) is safe when the argument is optional.
The Core Methods
A Set exposes a small API. The table lists each member and what it returns. The return values matter more than they seem to, because they decide which calls you can chain.
| Member | Purpose | Returns |
|---|---|---|
| `add(value)` | Insert a value if it is not already present | The same `Set` |
| `has(value)` | Check membership | `true` or `false` |
| `delete(value)` | Remove a value | `true` if it was present, otherwise `false` |
| `clear()` | Remove every value | `undefined` |
| `size` | Number of values (a property, not a method) | A number |
Here is a worked example that uses each of them.
const online = new Set();
online.add('ana').add('ben').add('ana'); // chaining works because add returns the Set
console.log(online.size); // 2
console.log(online.has('ben')); // true
console.log(online.has('cara')); // false
console.log(online.delete('ben')); // true
console.log(online.delete('ben')); // false, already gone
console.log(online.size); // 1
online.clear();
console.log(online.size); // 0Adding a value that is already present does nothing, and it does not throw. Because nothing is reported, you can't tell from the return value of add whether anything changed. If you need to know, check has first or compare size before and after:
function addAndReport(set, value) {
const before = set.size;
set.add(value);
return set.size > before; // true if the value was new
}
const seen = new Set();
console.log(addAndReport(seen, 42)); // true
console.log(addAndReport(seen, 42)); // falseMembership Flow
The diagram shows what add and delete do with a value, depending on whether it is already in the set.
A Set remembers the order in which values were first added. Adding an existing value again does not move it to the end. If you delete a value and add it back, it goes to the end like a new value. Insertion order is covered in more detail in the chapter on iterating sets.
Objects in a Set
Primitive values such as numbers and strings are compared by value. Objects are compared by reference. Two objects that look the same are still different values, and the set stores both.
const team = new Set();
team.add({ name: 'ana' });
team.add({ name: 'ana' });
console.log(team.size); // 2, two distinct objects
const ben = { name: 'ben' };
team.add(ben);
team.add(ben);
console.log(team.size); // 3, the same reference is added once
console.log(team.has(ben)); // true
console.log(team.has({ name: 'ben' })); // false, a new objectThis leads to a common bug: you build an object literal to look something up, and has returns false. To look up an object, keep a reference to the original object. If you need to compare objects by their content, store a primitive that stands for the object, such as an ID string, instead of the object itself.
Changing an object after you add it does not affect membership. The set holds the reference, and the reference doesn't change:
const item = { qty: 1 };
const cart = new Set([item]);
item.qty = 5;
console.log(cart.has(item)); // trueA Set also holds a strong reference to every object in it. As long as the set is reachable, its objects can't be garbage-collected, even if nothing else in the program uses them. A long-lived set that you only ever add to will keep growing in memory. Later chapters introduce WeakSet for cases where that is a problem.
What a Set Does Not Do
A Set deliberately leaves out some array features:
- No indexed access.
set[0]isundefined. If you need positions, convert the set to an array first. - No way to update a value in place. To replace a value, delete the old one and add the new one.
- No array methods. A
Sethas nomaporfiltermethod. Spread it into an array first, or use the iterator helpers covered in the iteration chapter.
const ids = new Set([10, 20, 30]);
console.log(ids[0]); // undefined
console.log([...ids][0]); // 10
ids.delete(20);
ids.add(25);
console.log([...ids]); // [10, 30, 25]Exercise
What does this code log, and why? const s = new Set('banana'); s.add('b'); console.log(s.size);
Show answer
It logs 3. The string 'banana' is iterable, so the constructor adds its characters: 'b', 'a', 'n'. Repeated characters are skipped. Adding 'b' again changes nothing because it is already present.
Exercise
Write a function firstRepeat(arr) that returns the first value in an array that appears a second time, or undefined if none does. Use a Set.
Show answer
function firstRepeat(arr) { const seen = new Set(); for (const v of arr) { if (seen.has(v)) return v; seen.add(v); } return undefined; } For example, firstRepeat([3, 1, 4, 1, 5]) returns 1. Each has and add takes near constant time, so the whole function runs in linear time.
Exercise
A developer writes const tags = new Set(); tags.add({ id: 7 }); console.log(tags.has({ id: 7 })); and expects true. What is logged, and how should they fix it?
Show answer
It logs false. Objects are compared by reference, and the second literal is a new object. To fix it, keep a reference to the original object and pass that reference to has, or store the primitive id (7) in the Set instead of the object.
Exercise
What do s.add(1) and s.delete(1) return, and which one can you chain?
Show answer
add returns the Set itself, so calls like s.add(1).add(2) chain. delete returns a boolean: true if the value was removed, false if it was not present. You cannot chain another Set method onto the result of delete.