Data #3b — Set in JavaScript

Set stores unique values with O(1) membership checks. Practical guide with patterns for deduplication, visited tracking, set operations (union/intersection/difference), and circular reference detection.

9 min read
JavaScript
Set
Data
ES6

TABLE OF CONTENTS

Set is JavaScript's collection of unique values. Any value can be a member — primitives, objects, functions. Sets give you O(1) membership tests, automatic deduplication, and are iterable in insertion order. They're used in interviews for dedup, visited tracking, and set operations.

Related: Data #3 — Map, Set, WeakMap, WeakSet Polyfills implements Set from scratch.


1. Why Set Over Array?

Arrays require O(N) to check membership and don't enforce uniqueness:

Loading editor...


2. Creating a Set

Loading editor...


3. Basic Operations

Loading editor...

add() returns the Set itself — chainable:

Loading editor...


4. Iteration

Set is iterable and preserves insertion order:

Loading editor...

keys() exists on Set only for API compatibility with Map. Both keys() and values() return the same iterator.


5. Object Values and Reference Equality

Object membership uses reference equality — same reference = same member:

Loading editor...


6. NaN and -0

Set uses SameValueZero comparison — NaN equals NaN, and +0 equals -0:

Loading editor...


7. Common Interview Patterns

Deduplicate an Array

Loading editor...

Track Visited Objects (Circular Reference Detection)

Loading editor...

Interview use: Circular reference detection in deep clone (#28 — though typically uses WeakSet/WeakMap), graph traversal.

Set Operations (Union, Intersection, Difference)

Loading editor...

Omit Keys Set (#15)

Loading editor...


8. Converting Between Set and Array

Loading editor...


9. WeakSet — When References Shouldn't Prevent GC

WeakSet only holds objects and doesn't prevent garbage collection:

Loading editor...

WeakSet is not iterable, has no size, and only has add, has, and delete. It's designed exclusively for "have I seen this object before?" use cases.


Quick Reference

MethodWhat It Does
new Set(iterable?)Create Set
set.add(value)Add value (returns set)
set.has(value)Check membership
set.delete(value)Remove value
set.clear()Remove all
set.sizeNumber of values
set.forEach(fn)Iterate
set.keys() / set.values()Values iterator
set.entries()[v, v] iterator (Map compat)

Interview Tips

  • Use Set for O(1) membershipset.has(x) beats array.includes(x) for frequent checks.
  • Use Set for dedup[...new Set(arr)] is the idiomatic one-liner.
  • Use WeakSet for "visited" tracking — it avoids memory leaks when objects are discarded.
  • Set handles NaN correctlyset.add(NaN); set.add(NaN); stores it once.

Related Articles


Let's Connect

© 2026 Naveen Karthik // Built with React & MUI