A Map is an ordered collection of key-value pairs where any data type (primitives, objects, functions) can be used as a key. Unlike plain objects, Map keys maintain insertion order and provide direct size tracking.
Map vs Plain Object Comparisonflowchart TD
Comparison["Dictionary Decision"] --> PlainObj["Plain Object {}"]
Comparison --> MapObj["Map Instance new Map()"]
PlainObj --> K1["Keys restricted to Strings / Symbols"]
PlainObj --> K2["No direct size property (Object.keys().length)"]
PlainObj --> K3["Inherits Prototype keys"]
MapObj --> M1["Keys can be ANY type (Objects, Functions, Primitives)"]
MapObj --> M2["Direct map.size property"]
MapObj --> M3["Guaranteed insertion order iteration"]
| Method / Property | Signature | Description |
|---|---|---|
size |
map.size |
Returns count of key-value pairs. |
set(key, val) |
map.set(k, v) |
Adds/updates key-value pair (chainable). |
get(key) |
map.get(k) |
Retrieves value for key; returns undefined if absent. |
has(key) |
map.has(k) |
Returns boolean indicating if key exists. |
delete(key) |
map.delete(k) |
Removes key-value pair. |
// Demonstrating Map usage with object keys and iteration
// 1. Creating Map with Object Keys
const userSessions = new Map();
const userAlex = { id: 101, name: "Alex" };
const userSarah = { id: 102, name: "Sarah" };
// Using objects as keys!
userSessions.set(userAlex, { token: "TOKEN_ABC", loginTime: "10:00 AM" });
userSessions.set(userSarah, { token: "TOKEN_XYZ", loginTime: "10:15 AM" });
console.log(`Map Size: ${userSessions.size}`);
console.log("Alex Session Info:", userSessions.get(userAlex));
// 2. Iterating Over Map
console.log("
--- Map Iteration ---");
for (const [userObj, session] of userSessions) {
console.log(`User: ${userObj.name} -> Token: ${session.token}`);
}
// 3. Converting Map to Object & Array
const mapArray = Array.from(userSessions.entries());
console.log("Map converted to Entries Array:", mapArray.length);
Map when Keys are Dynamic or Non-Strings: Use Map if key names are unknown at runtime or if keys must be object instances (e.g. DOM nodes).Map.has() Over map.get() !== undefined: A Map can explicitly store undefined as a value; use .has(key) to test key existence accurately.Map will not be garbage collected even if references elsewhere are deleted. Use WeakMap if keys should be garbage-collectable.Create a Map where DOM element nodes serve as keys storing event count metadata numbers.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.