What does Set do?
What Set is
Setis a built-in data structure in JavaScript (introduced in ES6) that stores unique values of any type.
That is, Set cannot contain repeating elements.
Example:
javascript
const set = new Set();
set.add(1);
set.add(2);
set.add(2); // a duplicate - won't be added
set.add('hello');
console.log(set); // Set(3) {1, 2, 'hello'}
console.log(set.size); // 3Main methods
| Method / property | What it does | Example |
|---|---|---|
add(value) | Adds an element | set.add(10) |
has(value) | Checks for presence | set.has(10) -> true |
delete(value) | Removes an element | set.delete(10) |
clear() | Clears the Set | set.clear() |
size | Number of elements | set.size |
Iteration
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 thingExample: 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]A very common and practical trick -
new Set()+ spread...= "remove duplicates".
Example: intersection of 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}Example: difference of sets
javascript
const difference = new Set([...a].filter(x => !b.has(x)));
console.log(difference); // Set(1) {1}How Set differs from an array
| Feature | Array | Set |
|---|---|---|
| Duplicates | Allowed | Not allowed |
| Order | Ordered | Ordered (by insertion) |
| Checking for presence | arr.includes(x) (O(n)) | set.has(x) (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 Set
Use Set if:
- you need to store only unique values;
- it's important to quickly check for the presence of elements;
- you don't need indexing (positions don't matter);
- you need to easily remove or clear elements.
Briefly
| What | Description |
|---|---|
| Type | A collection of unique values |
| Key methods | .add(), .has(), .delete(), .clear() |
| Size | size |
| Converting to an array | [...set] |
| Main difference from an array | Only unique elements, and fast lookup operations |
In simpler terms:
An array is a list where repeats are allowed. A Set is a set where every element is unique.
Setis ideal for filtering, searching, and working with unique data.
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.