Map iteration
Learn to iterate a Map with for...of, entries and forEach.
Looping over a Map
When you loop over a Map with for...of, each step gives you a [key, value] array. You can destructure it: for (const [key, value] of map).
Map iterates keys in insertion order; this order is always consistent. Loop controls like break and continue work with Map as usual.
entries, keys, values, forEach
Map has three iterator methods: entries() returns [key, value] pairs, keys() returns just keys, and values() returns just values. forEach((value, key) => {...}) runs a callback for each entry.
Note: in forEach the parameter order is value first, then key. This matches array forEach but differs from Map's [key, value] order.
Exercise Iterate a Map with for...of
Create a Map called prices. Add 5 under key "apple" and 7 under key "banana". Loop over the Map with for...of using [item, price] destructuring and log each pair with console.log(item, price).
Show example solution
const prices = new Map();
prices.set("apple", 5);
prices.set("banana", 7);
for (const [item, price] of prices) {
console.log(item, price);
}
Test yourself
-
In `for (const x of map)`, what is `x`?
- Only the key
- Only the value
- The Map itself
- A [key, value] array
Show answer
A [key, value] array — Correct. for...of yields a [key, value] pair at each step by default.
-
for...of destructuring
const prices = new Map(); prices.set("apple", 5); for (const [item, price] ____ prices) { console.log(item, price); }Show answer
const prices = new Map(); prices.set("apple", 5); for (const [item, price] of prices) { console.log(item, price); } -
What is the parameter order in Map forEach?
- (key, value)
- (value, key)
- only value
- only key
Show answer
(value, key) — Correct. Map forEach passes value first, then key.
-
Match the Map iteration methods
- entries()
- [key, value] pairs
- keys()
- Only keys
- values()
- Only values
- forEach
- Callback iteration