Reading — step 1 of 7
Learn
Plain objects ARE often used as maps in JavaScript, but the built-in Map and Set (ES2015) are better for most cases. They preserve insertion order, accept any key type, and have a clean iteration API.
Set — unique values
From an array (with dedup):
This is the canonical JS dedup pattern.
Iterate Set:
Map — key/value pairs (any key type)
With initial entries:
Why prefer Map over plain object?
Map keys don't collide with prototype properties. Map preserves insertion order reliably across all JS engines. Map can have non-string keys.
Iterate Map:
When to use which
| Use case | Best choice |
|---|---|
| Dedup a list | [...new Set(arr)] |
| Membership check on a fixed list | Set |
| Counter/frequency map | Map |
| Object-keyed lookup | Map |
| Configuration / fixed-shape data | Plain object |
| JSON-serializable data | Plain object (Map doesn't JSON-serialize) |
Iteration protocols (recap)
Anything that has [Symbol.iterator]() is iterable:
- Strings
- Arrays
- Sets
- Maps
- Generators
- TypedArrays
- NodeList (DOM)
- arguments
Iterables work with:
for...of- Spread
[...iter],{...iter}(limited) - Destructuring
[a, b] = iter Array.from(iter)Promise.all,SetandMapconstructors
Plain objects are NOT iterable by default. Use Object.entries(obj), Object.keys(obj), Object.values(obj) to get an array.
Common mistakes
- Plain object as a map with arbitrary string keys — collisions with
__proto__,toString,constructor. Use Map orObject.create(null). - JSON.stringify on a Map — produces
{}. Convert to a plain object first or use a custom replacer. - Set/Map for primitive lookups when you'd be fine with an object — slight overhead. For tiny fixed lists, plain object/array can be fine.
- Comparing Sets with === — references.
new Set([1]) === new Set([1])is false. Compare contents manually. - Forgetting Sets dedupe by SameValueZero —
Settreats NaN as equal to NaN (unlike ===), but objects are by reference.
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…