Data #3a — Map in JavaScript

Map is the true key-value store — any type as key, insertion-ordered iteration, O(1) lookups. Practical guide with patterns for frequency counters, caches, event registries, and data merging.

10 min read
JavaScript
Map
Data
ES6

TABLE OF CONTENTS

Map is JavaScript's true key-value data structure. Unlike objects, Map keys can be any type — objects, functions, numbers — and entries stay in insertion order. It's used in interviews for caches, frequency counters, event listeners, and anywhere you need a reliable dictionary.

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


1. Why Map Over Object?

Objects have three problems as dictionaries:

Loading editor...


2. Creating a Map

Loading editor...


3. Basic Operations

Loading editor...


4. Iteration

Map is iterable and preserves insertion order:

Loading editor...


5. Object Keys

Object keys use reference equality — same reference = same key:

Loading editor...

This is why Map is perfect for storing metadata about objects without modifying the objects themselves:

Loading editor...


6. NaN and -0 as Keys

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

Loading editor...

Interview use: Memoize (#10) — NaN arguments properly hit the same cache entry.


7. Map vs Object Decision Guide

MapObject
Key typesAny valueString or Symbol only
Insertion orderGuaranteedMostly guaranteed (ES2015+)
Sizemap.sizeObject.keys(obj).length
Iterationfor...of, forEachfor...in + hasOwnProperty
Performance (frequent add/delete)FasterSlower
JSON serializationMust convert firstNative JSON.stringify
Prototype collisionsNonetoString, constructor, etc.

Rule of thumb: Use Map for dictionaries with dynamic keys (especially non-string keys). Use objects for fixed-schema data and JSON serialization.


8. Common Interview Patterns

Frequency Counter

Loading editor...

Two-Sum (O(N))

Loading editor...

Event Listener Registry (#22)

Loading editor...

Data Merging by Key (#25)

Loading editor...


Quick Reference

MethodWhat It Does
new Map(entries?)Create Map (optionally from [k,v] pairs)
map.set(key, value)Add or update entry
map.get(key)Get value (or undefined)
map.has(key)Check if key exists
map.delete(key)Remove entry
map.clear()Remove all entries
map.sizeNumber of entries
map.keys()Iterator of keys
map.values()Iterator of values
map.entries()Iterator of [key, value] pairs
map.forEach(fn)Iterate with callback

Interview Tips

  • Use Map for non-string keys — "I'll use a Map so I can key by the actual object reference, not its string representation."
  • Map preserves insertion order — count-by preserves the order keys are first seen.
  • map.get() returns undefined for missing keys — distinguish from stored undefined with map.has().
  • Use Map for event listenersMap<string, listener[]> avoids prototype collisions on event names.

Related Articles


Let's Connect

© 2026 Naveen Karthik // Built with React & MUI