Chapter 11 Cheatsheet: Maps

This cheatsheet summarizes the mechanics of the JavaScript Map object covered in Chapter 11.

Core Operations

A Map is a specialized collection strictly for key-value pairs.

const userRoles = new Map();

// Add or update an entry
userRoles.set("Alice", "Admin");
userRoles.set("Bob", "User");

// Retrieve an entry
console.log(userRoles.get("Alice")); // "Admin"

// Delete an entry
userRoles.delete("Bob");

Complex Keys

Unlike Objects, Maps can use anything as a key—including other arrays or objects. However, you must use the exact same variable reference to retrieve the data later.

const map = new Map();
const myKeyObj = { id: 1 };

map.set(myKeyObj, "Data loaded");
console.log(map.get(myKeyObj)); // "Data loaded"

Map vs Object Quick Reference

Feature Map Object
Key Types Any data type Strings & Symbols only
Order Strictly insertion order Unreliable order
Size map.size property Must calculate manually
Iteration Directly iterable via for...of Requires Object.entries()
Performance Optimized for frequent inserts/deletes Better for static configurations