Map.prototype.get()
Straightforward reading, with one gap: undefined means both "not there" and "there, holding undefined". has() is how you tell them apart.
Demo
Present keys return their value; absent keys return undefined. The third case shows null is returned as null — only a genuinely missing key gives undefined. The fourth is the one to watch: the Map was built with the NUMBER 1 as its key, and looking up the STRING '1' misses entirely. A plain object would have found it, because object keys are always strings. Map does no coercion, which is a feature and a trap in equal measure.
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
| key | any | yes | The key to look up, matched by SameValueZero. No coercion happens — 1 and "1" are different keys. |
Return value
any — The stored value, or undefined when the key is absent. Those two cases are indistinguishable if you ever store undefined.
Common patterns
const count = map.get(key) ?? 0;
if (!map.has(key)) map.set(key, []); map.get(key).push(item);
const present = map.has(key); const value = map.get(key);
Examples
Pitfalls
new Map([["a", undefined]]).get("a")
new Map([["a", undefined]]).has("a")
new Map([[1, "x"]]).get("1")
new Map([[1, "x"]]).get(Number("1"))
if (!m.has(k)) m.set(k, []); m.get(k).push(x);
let a = m.get(k); if (!a) m.set(k, a = []); a.push(x);
const m = new Map([["a", 1]]); m["a"]
m.get("a")
When to use
- Reading a value by a key of any type
- Lookups where keys must not be coerced to strings
- Caches and indexes keyed by objects or numbers
- You only need to know whether the key exists → has
- Values may be undefined and that matters → pair with has
- The data is a fixed record → an object, with property access
- You want a default without a check → Object.groupBy, or ?? at the call site
Notes
FAQ
Nullish coalescing on the result. Use ?? rather than || so that a legitimately stored 0, empty string or false is not replaced by the default.
const n = map.get(key) ?? 0; // keeps a stored 0 const bad = map.get(key) || 0; // replaces it