JavaScript Maps
A `Map` is a collection of key-value pairs, similar to an object, but keys can be of any type (not just strings) and Maps maintain insertion order reliably.
Use `set(key, value)` to add entries, `get(key)` to retrieve, `has(key)` to check existence, and `size` to get the count.
Map vs Object
Unlike plain objects, Maps allow any value (objects, functions, numbers) as keys and have a guaranteed iteration order. Maps also perform better for frequent additions/removals.
Iterating a Map
`for (const [key, value] of map)` destructures each entry, or use `map.forEach((value, key) => {...})`.
let scores = new Map();
scores.set("Alice", 90);
scores.set("Bob", 85);
console.log(scores.get("Alice"));90set() adds entries; get() retrieves a value by key.
let map = new Map([["a", 1], ["b", 2]]);
for (const [key, value] of map) {
console.log(key, value);
}a 1
b 2Maps can be constructed from an array of [key, value] pairs and iterated directly.
Key points
- Maps store key-value pairs where keys can be any type.
- set(), get(), has(), delete() manage Map entries.
- size gives the number of entries (not length).
- Maps guarantee insertion order during iteration.
