JavaScript Map: Key Identity and Ordered Entries
Quick answer
Map stores key–value pairs with arbitrary JavaScript values as keys. Object keys are matched by identity rather than by their property contents.
How it works
Create a map with new Map() or an iterable of two-element entries. set(key, value) inserts or replaces an entry and returns the map. get(key) returns the stored value or undefined; has(key) distinguishes a missing key from a stored undefined. size counts entries. Unlike ordinary object properties, numeric and string keys remain distinct.
const m = new Map([[1, "number"], ["1", "text"]]); console.log(m.size, m.get(1), m.get("1"));Expected output in Node.js:
2 number textNumber and string keys are different.
const key = {id: 1}; const m = new Map([[key, undefined]]); console.log(m.has(key), m.has({id: 1}), m.get(key));Expected output in Node.js:
true false undefinedThe first key exists even though its value is undefined.
Common mistakes
Do not write map[key] = value: that sets an ordinary property, not a map entry. Recreating an object with the same fields does not recreate its identity.
Practice
Count occurrences of labels in an input array; use Map so a label that is a string does not collide with object property names.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
JavaScript Map: Key Identity and Ordered Entries — Knowledge Check
Apply the taught concept and predict the output.
Which operation distinguishes an absent Map key from a stored undefined?
What does Map.prototype.set return?
How is an object key matched by Map?
What is the exact console output in JavaScript Map: Key Identity and Ordered Entries example 1?
const m = new Map([[1, "number"], ["1", "text"]]); console.log(m.size, m.get(1), m.get("1"));What is the exact console output in JavaScript Map: Key Identity and Ordered Entries example 2?
const key = {id: 1}; const m = new Map([[key, undefined]]); console.log(m.has(key), m.has({id: 1}), m.get(key));