Maps
Overview
The Map object (introduced in ES6) holds key-value pairs just like standard Objects. However, Maps solve three major flaws of standard Objects:
1. Key Types: Object keys must be Strings or Symbols. Map keys can be absolutely ANYTHING (Functions, Arrays, Objects, Numbers).
2. Order: Maps guarantee that insertion order is strictly preserved.
3. Size: Maps have a built-in .size property, making it instantly easy to see how many items are stored.
Syntax
const inventory = new Map();
// set(key, value)
inventory.set("apples", 50);
inventory.set("bananas", 30);
// get(key)
console.log(inventory.get("apples")); // 50
// has(key) - Instant boolean check
console.log(inventory.has("oranges")); // false
console.log(inventory.size); // 2const user1 = { id: 1 };
const user2 = { id: 2 };
const metadata = new Map();
// Using the actual objects as keys!
metadata.set(user1, { lastLogin: "Tuesday", ip: "192.168.1.1" });
console.log(metadata.get(user1).lastLogin); // "Tuesday"Common Pitfalls
- Using
map.key = valuesyntax. While this technically runs (because Maps are objects), it completely bypasses the Map data structure and just assigns a standard object property, meaning.sizewon't update and.has()won't work. Always use.set()and.get().
Interview Questions
Use a Map when: 1. You frequently add and remove key-value pairs (Maps are optimized for this). 2. You need keys that are not strings (like numbers or objects). 3. The exact insertion order of the keys must be preserved. 4. You need to easily iterate or check the size.
Real-World Example
Building an in-memory cache mechanism. The Map stores API request URLs as the keys, and the JSON responses as the values. When a request is made, you instantly check if the URL exists in the Map before hitting the network.
if (cache.has(url)) return cache.get(url);
const data = await fetch(url);
cache.set(url, data);Check Your Knowledge
Test your understanding of Maps with these quick questions.