The Set collection in JavaScript
Set is a built in JavaScript data structure, introduced in ES6, that stores only unique values of any type. In other words, a Set cannot contain duplicate elements: trying to add a duplicate simply changes nothing.
Theory
TL;DR
- A
Setis a collection of unique values, duplicates are ignored. - Methods:
add,has,delete,clear; the size comes fromsize. - Insertion order is preserved and the collection is iterable.
set.has(x)runs in O(1), unlikearr.includes(x)which is O(n).- A
Sethas no indexes,set[0]returns nothing. - The classic trick:
[...new Set(arr)]removes duplicates from an array.
Quick example
javascript
const set = new Set();
set.add(1);
set.add(2);
set.add(2); // duplicate, will not be added
set.add('hello');
console.log(set); // Set(3) {1, 2, 'hello'}
console.log(set.size); // 3Core methods
| Method / property | What it does | Example |
|---|---|---|
add(value) | Adds an element | set.add(10) |
has(value) | Checks presence | set.has(10) returns true |
delete(value) | Removes an element | set.delete(10) |
clear() | Empties the Set | set.clear() |
size | Number of elements | set.size |
add() returns the Set itself, so calls can be chained: set.add(1).add(2).
Iterating a Set
javascript
const set = new Set(['a', 'b', 'c']);
for (const value of set) {
console.log(value);
}
// a
// b
// c
set.forEach(v => console.log(v)); // the same thingIn forEach the callback receives (value, value, set): the second argument repeats the first, because a Set has no keys.
Practical patterns
Removing duplicates from an array:
javascript
const numbers = [1, 2, 2, 3, 3, 4];
const unique = [...new Set(numbers)];
console.log(unique); // [1, 2, 3, 4]This is a very common and practical trick: new Set() plus the spread ... equals "drop the duplicates".
Intersection of two sets:
javascript
const a = new Set([1, 2, 3]);
const b = new Set([2, 3, 4]);
const intersection = new Set([...a].filter(x => b.has(x)));
console.log(intersection); // Set(2) {2, 3}Difference of two sets:
javascript
const difference = new Set([...a].filter(x => !b.has(x)));
console.log(difference); // Set(1) {1}How a Set differs from an array
| Feature | Array | Set |
|---|---|---|
| Duplicates | Allowed | Not allowed |
| Order | Ordered | Ordered (by insertion) |
| Presence check | arr.includes(x) in O(n) | set.has(x) in O(1) |
| Removing an element | Slow (splice) | Fast (delete()) |
| Indexing | Yes (arr[0]) | No |
| Size | arr.length | set.size |
| Iteration | for, forEach, map | for...of, forEach |
When to use a Set
Reach for a Set when:
- you need to store only unique values;
- fast presence checks matter;
- indexing is not needed, positions do not matter;
- elements have to be removed or cleared easily.
In short:
| What | Description |
|---|---|
| Type | A collection of unique values |
| Key methods | .add(), .has(), .delete(), .clear() |
| Size | size |
| Conversion to an array | [...set] |
| Main difference from an array | Unique elements only and fast lookups |
Common mistakes
- Expecting a
Setto deduplicate objects. Uniqueness is decided by reference, so two literals{ id: 1 }with identical content stay two separate elements. - Accessing by index.
set[0]returnsundefined; to read an element by position, convert the collection first:[...set][0]. - Confusing
sizeandlength. ASetonly hassize, and it is a property, not a method. - Calling array methods directly.
set.map(...)andset.filter(...)do not exist; use[...set].map(...)instead. - Forgetting about
NaNand-0. ASettreatsNaNas equal toNaN, so only one such element is stored, and-0and0are kept as a single value. - Serialising a
SetwithJSON.stringify. The result is{}; convert the collection into an array before serialising.
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.