Skip to main content

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 Set is a collection of unique values, duplicates are ignored.
  • Methods: add, has, delete, clear; the size comes from size.
  • Insertion order is preserved and the collection is iterable.
  • set.has(x) runs in O(1), unlike arr.includes(x) which is O(n).
  • A Set has 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); // 3

Core methods

Method / propertyWhat it doesExample
add(value)Adds an elementset.add(10)
has(value)Checks presenceset.has(10) returns true
delete(value)Removes an elementset.delete(10)
clear()Empties the Setset.clear()
sizeNumber of elementsset.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 thing

In 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

FeatureArraySet
DuplicatesAllowedNot allowed
OrderOrderedOrdered (by insertion)
Presence checkarr.includes(x) in O(n)set.has(x) in O(1)
Removing an elementSlow (splice)Fast (delete())
IndexingYes (arr[0])No
Sizearr.lengthset.size
Iterationfor, forEach, mapfor...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:

WhatDescription
TypeA collection of unique values
Key methods.add(), .has(), .delete(), .clear()
Sizesize
Conversion to an array[...set]
Main difference from an arrayUnique elements only and fast lookups

Common mistakes

  • Expecting a Set to deduplicate objects. Uniqueness is decided by reference, so two literals { id: 1 } with identical content stay two separate elements.
  • Accessing by index. set[0] returns undefined; to read an element by position, convert the collection first: [...set][0].
  • Confusing size and length. A Set only has size, and it is a property, not a method.
  • Calling array methods directly. set.map(...) and set.filter(...) do not exist; use [...set].map(...) instead.
  • Forgetting about NaN and -0. A Set treats NaN as equal to NaN, so only one such element is stored, and -0 and 0 are kept as a single value.
  • Serialising a Set with JSON.stringify. The result is {}; convert the collection into an array before serialising.

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.