Codectionary / Developer documentation / JavaScript

Sets

A Set is a collection of unique values of any type - unlike an array, it automatically prevents duplicates. Sets maintain insertion order and provide efficient add, delete, and lookup operations. They are ideal for deduplicating data or tracking membership without caring about order or indexed access.

Syntax

const mySet = new Set([values]);
mySet.add(value);
mySet.has(value);

Examples

Basic Set Operations

Creating a Set and using its core methods.

const mySet = new Set();

mySet.add(1);
mySet.add(2);
mySet.add(2); // ignored - 2 is already in the set
mySet.add(3);

console.log(mySet.size);      // 3
console.log(mySet.has(2));    // true
mySet.delete(2);
console.log(mySet.has(2));    // false

Deduplicating an Array

One of the most common uses of Set - removing duplicates.

const numbers = [1, 2, 2, 3, 4, 4, 5];
const unique = [...new Set(numbers)];
console.log(unique); // [1, 2, 3, 4, 5]

Iterating a Set

Sets are iterable and work with for...of.

const tags = new Set(["js", "web", "css"]);

for (const tag of tags) {
  console.log(tag);
}
// js, web, css - in insertion order

tags.forEach(tag => console.log(tag)); // also works

Best practices

  • Use Set instead of an array when you need to guarantee uniqueness and do not need indexed access
  • Use the [...new Set(array)] pattern as the concise standard way to deduplicate an array
  • Remember Set uses the same equality as ===, with the one exception that NaN is treated as equal to itself
  • Use has() for membership checks instead of array includes() - Set lookups are generally faster for large collections

At a glance

Purpose
Application logic and interaction
File extension
.js ยท .mjs
Runs in
Browsers and JavaScript runtimes
Usually used with
HTML, CSS and Web APIs

Specifications & further reading

Related JavaScript documentation