- Home
- /
- Tutorials
- /
- DSA Tutorial
- /
- Hash Maps and Sets in JavaScript
Hash Maps and Sets
Hash Maps and Sets in JavaScript
If you learn one structure properly, make it the hash map. More interview problems collapse from O(n squared) to O(n) with a Map than with anything else in this tutorial.
What makes it fast
A hash map turns a key into a number, and that number is a position. It does not search - it calculates where the value should be and looks there. That is why lookup is O(1) whether the map holds ten entries or ten million.
The cost is memory, and the fact that the order is not something you should reason about beyond insertion order.
Map, Set, and plain objects
The three, and when each fits
javascript
// Map — any key type, remembers insertion order, has .size
const scores = new Map()
scores.set("ada", 90)
scores.set("grace", 95)
scores.get("ada") // 90
scores.has("ada") // true
scores.size // 2
// Set — membership only, no values
const seen = new Set([1, 2, 2, 3])
seen.has(2) // true
seen.size // 3, duplicates collapse
// Plain object — string keys only, and it inherits
const counts = {}
counts.ada = 90