Skip to main content

What does Set do?

What Set is

Set is 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); // 3

Main methods

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

Example: 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

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

WhatDescription
TypeA collection of unique values
Key methods.add(), .has(), .delete(), .clear()
Sizesize
Converting to an array[...set]
Main difference from an arrayOnly 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. Set is ideal for filtering, searching, and working with unique data.

Short Answer

Interview ready
Premium

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