Learn JavaScript
❯ collections.set_collection

Set in JavaScript

$concept

Set holds unique values with SameValueZero equality (NaN equals NaN here!) in insertion order: add/append, has tests, delete removes, size counts, clear empties. Unlike arrays, membership is effectively O(1) and duplicates structurally impossible.

Canonical uses: deduplication ([...new Set(arr)]), membership testing in hot paths, and set algebra via helpers (union/intersection as filter/has compositions). Values can be anything — but objects compare by reference, so two identical literals are two members.

$how it works
1

Unique by construction

add() ignores present values — duplicates cannot exist, no manual checking.

2

O(1) membership

has() answers in constant time — the performance reason Sets replace includes() scans.

3

NaN equals NaN

SameValueZero unites NaN with itself — unlike ===, like includes.

4

Objects by reference

{a:1} !== {a:1} as members — distinct objects never deduplicate, however equal-looking.

$example
let seen = new Set([1, 2, 2, 3]);
console.log(seen.size, seen.has(2));
console.log([...seen]);
Output
3 true
[ 1, 2, 3 ]
1Construction deduplicates immediately — {1, 2, 3}, so size reports 3 and has(2) is true.
2Spreading iterates insertion order into [1, 2, 3] — the duplicate 2 appears once.
3Uniqueness, membership, and ordered iteration in four lines.
$use cases
Deduplication via [...new Set(arr)]
Fast membership tests replacing linear includes()
Seen-sets in graph traversal and visited tracking
Set algebra (union/intersection/difference) through composition

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in JavaScript yourself — building beats watching.