Sub topic 5
Iterating Maps: keys, values, entries, and forEach
This chapter assumes you know for...of loops, array destructuring, the spread operator, and the basic Map methods set, get, has, and delete from the Map fundamentals chapter. It explains how Maps hand you their contents, what order the entries come in, and what happens when the Map changes while you are looping over it.
The Ordering Guarantee
A Map remembers the order in which each key was first inserted, and iteration always follows that order. The specification guarantees this, so it is not an engine detail you happen to observe. Two rules decide where an entry sits:
- Calling
seton an existing key updates its value and leaves its position unchanged. - Deleting a key and then setting it again counts as a new insertion, so the key moves to the end.
const scores = new Map();
scores.set('ana', 10).set('ben', 7).set('cy', 12);
scores.set('ana', 15); // update: position kept
console.log([...scores.keys()]); // ['ana', 'ben', 'cy']
scores.delete('ben');
scores.set('ben', 9); // re-insert: moves to end
console.log([...scores.keys()]); // ['ana', 'cy', 'ben']Number-like keys follow the same rule. A plain object lists integer-like keys in ascending numeric order. A Map does not reorder anything.
The Iterator Methods
A Map has three methods that return iterators. An iterator is an object that produces values one at a time through its next method, and you usually consume it with for...of or spread.
| Method | Yields | Typical use |
|---|---|---|
| `map.keys()` | each key | checking or listing keys |
| `map.values()` | each value | totals, searches over values |
| `map.entries()` | `[key, value]` arrays | most loops |
| `map[Symbol.iterator]()` | same as `entries()` | what `for...of map` calls |
Because the default iterator is entries, these two loops behave the same:
const prices = new Map([['tea', 3], ['coffee', 4], ['juice', 5]]);
for (const [item, price] of prices) {
console.log(`${item}: $${price}`);
}
for (const [item, price] of prices.entries()) {
console.log(`${item}: $${price}`);
}
console.log(prices[Symbol.iterator] === prices.entries); // trueDestructuring [item, price] in the loop head is the usual style. Without it you get a two-element array and have to write entry[0] and entry[1].
Iterators are single-use
Each call to keys(), values(), or entries() returns a fresh iterator. Once you have read an iterator to the end, it stays exhausted. This catches people who save an iterator in a variable and use it twice.
const m = new Map([['a', 1], ['b', 2]]);
const keyIter = m.keys();
console.log([...keyIter]); // ['a', 'b']
console.log([...keyIter]); // [] (already exhausted)
console.log([...m.keys()]); // ['a', 'b'] (new iterator)When you need the keys more than once, either call m.keys() again or copy them into an array once with [...m.keys()].
Iterators are not arrays
m.values() gives you no map, filter, reduce, or length. You have three options:
const stock = new Map([['apples', 12], ['pears', 0], ['plums', 5]]);
// 1. Spread into an array, then use array methods
const total = [...stock.values()].reduce((sum, n) => sum + n, 0);
console.log(total); // 17
// 2. Array.from with a mapping function (no intermediate array)
const labels = Array.from(stock, ([name, qty]) => `${name} x${qty}`);
console.log(labels); // ['apples x12', 'pears x0', 'plums x5']
// 3. A plain loop, which can stop early
let firstEmpty;
for (const [name, qty] of stock) {
if (qty === 0) {
firstEmpty = name;
break;
}
}
console.log(firstEmpty); // 'pears'forEach
Map.prototype.forEach calls a function once per entry, in insertion order. The callback receives the value first, then the key, then the Map itself:
const roles = new Map([['ana', 'admin'], ['ben', 'editor']]);
roles.forEach((value, key, map) => {
console.log(`${key} is ${value} (of ${map.size})`);
});
// ana is admin (of 2)
// ben is editor (of 2)The argument order copies Array.prototype.forEach, where the element comes before the index. If you write (key, value) => out of habit, your names will be swapped and you get no error.
forEach differs from for...of in ways that affect your choice:
| Concern | `for...of` | `forEach` |
|---|---|---|
| Stop early | `break` or `return` | not possible without throwing |
| `await` inside | works in an `async` function | callbacks run without waiting |
| Argument order | you destructure `[key, value]` | `(value, key, map)` |
| Chaining | none | returns `undefined` |
The await case matters in practice. Inside forEach, an async callback returns a promise that forEach ignores, so the code after the loop runs before any of the awaited work has finished. Use for...of when each step must wait.
Changing a Map While Iterating
Map iterators are live. They walk the current entry list and do not take a snapshot, so changes made during the loop affect what the loop sees next:
- An entry added during iteration is visited, because it goes on the end.
- An entry deleted before the loop reaches it is not visited.
- Updating the value of a key that has not been visited yet means the loop sees the new value.
- Deleting the current entry is safe. The loop continues with the next one.
const queue = new Map([['a', 1], ['b', 2], ['c', 3]]);
for (const [key, value] of queue) {
console.log(key, value);
if (key === 'a') {
queue.delete('b'); // not yet visited: skipped
queue.set('d', 4); // appended: will be visited
queue.set('c', 30); // updated before visit
}
}
// a 1
// c 30
// d 4The safe-delete rule lets you prune a Map in place:
const sessions = new Map([['s1', 100], ['s2', 5], ['s3', 80]]);
const now = 90;
for (const [id, expiresAt] of sessions) {
if (expiresAt < now) sessions.delete(id);
}
console.log([...sessions.keys()]); // ['s1']A snapshot is also the right choice whenever the loop body must not see its own changes. for (const [k, v] of [...m]) iterates over a fixed array while you change m freely.
Reordering: Sorting a Map
A Map has no sort method. Because its order is its insertion order, you sort by building a new Map from sorted entries:
const wins = new Map([['ana', 3], ['ben', 7], ['cy', 5]]);
const byWinsDesc = new Map([...wins].sort((a, b) => b[1] - a[1]));
console.log([...byWinsDesc.keys()]); // ['ben', 'cy', 'ana']
const byName = new Map([...wins].sort(([a], [b]) => a.localeCompare(b)));
console.log([...byName.keys()]); // ['ana', 'ben', 'cy']The original wins Map keeps its order. Entries you add to byWinsDesc later go on the end and are not placed in sorted position, so sort again after changes if you need the order to hold.
Common Mistakes
- Writing
forEach((key, value) => ...). The value comes first. - Reusing an iterator stored in a variable after it is exhausted.
- Calling array methods such as
m.values().mapin a runtime without iterator helpers. Spread first. - Expecting
seton an existing key to move it to the end. Only delete followed by set moves a key. - Using
forEachwithasynccallbacks and expecting the loop to wait.
Exercise
Given const m = new Map([['x', 1], ['y', 2]]);, what does this print: m.set('x', 9); m.delete('y'); m.set('y', 3); m.set('z', 4); console.log([...m]);?
Show answer
[['x', 9], ['y', 3], ['z', 4]]. Setting 'x' updates its value in place. Deleting and re-setting 'y' moves it to the end, and 'z' is appended after it.
Exercise
Write a function keysWithValue(map, target) that returns an array of every key whose value is strictly equal to target, in insertion order, without using forEach.
Show answer
function keysWithValue(map, target) { const result = []; for (const [key, value] of map) { if (value === target) result.push(key); } return result; }. An alternative is [...map].filter(([, v]) => v === target).map(([k]) => k).
Exercise
A loop runs for (const [k, v] of m) { if (v < 0) { m.delete(k); m.set(k, 0); } }. Does it terminate, and what is the final order?
Show answer
It terminates. Each negative entry is moved to the end with the value 0. When the loop reaches it again, 0 is not less than 0, so it is left alone. The final order is the non-negative entries in their original order, followed by the formerly negative keys in the order they were moved.