Skip to main content

Hash Set

What a hash set is, how JavaScript Set works, and when you only need to know whether a value exists.

Andrews Ribeiro

Andrews Ribeiro

Founder & Engineer

What it is

A hash set stores unique values.

Unlike a hash map, the point here is not associating a key with a value.

The point is answering quickly:

“have I seen this value already?”

In JavaScript

Set is the direct implementation:

const seen = new Set<number>()

seen.add(3)
seen.has(3)

If you only care about existence, Set is usually simpler than Map.

When to use it

Use Set when you need to:

  • remove duplicates
  • track whether something has appeared
  • prevent repeated processing

Better question

Before using it, ask:

  1. do I only need existence, or also an associated value?
  2. am I avoiding duplicates or counting frequency?
  3. is the extra memory worth the faster lookup?

Keep exploring