JavaScript Reference ยท Collections
Map iteration
Reference for iterating a JavaScript Map: for...of, forEach(), keys(), values() and entries(), insertion order, spreading to arrays and changing a map while looping.
A Map is iterable, and it always walks its entries in insertion order. There are four ways to loop: for...of over the map itself (which gives [key, value] pairs), forEach(), and the three iterator methods keys(), values() and entries().
The iterator methods return live iterator objects, not arrays. Spread them ([...map.keys()]) or use Array.from() when you need an array.
for (const [key, value] of map) { /* ... */ } map.forEach((value, key) => { /* ... */ });
Try it
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Syntax
for (const [key, value] of map) { } map.forEach(callbackFn) map.forEach(callbackFn, thisArg) map.keys() map.values() map.entries() map[Symbol.iterator]() // same function as entries()
| Name | Description |
|---|---|
callbackFn |
Called once per entry as callbackFn(value, key, map). Note that the value comes first. |
thisArg |
Optional. The this value inside callbackFn (ignored by arrow functions). |
Return value: forEach() returns undefined. keys(), values() and entries() return a new iterator that is itself iterable.
Exceptions: forEach() throws a TypeError if callbackFn is not a function.
Usage notes
- Order is insertion order. Updating a key keeps its position; deleting and re-adding moves it to the end. That differs from plain objects, where integer-like keys are sorted first.
- Arguments of
forEach()matchArray.prototype.forEach(). The callback gets(value, key, map), so(value, key)is the reverse of the pairs you get fromfor...of. for...ofsupportsbreak,continueandawait;forEach()does not. Preferfor...ofwhen you may leave the loop early or call asynchronous code in order.- Live iteration. Entries added during the loop are visited; entries deleted before being reached are skipped. Avoid growing a map you are looping over.
- A map has no
map()orfilter(). Convert to an array, transform, and pass the result back intonew Map(...)as in the second example. - Iterators are single-use. Once exhausted, an iterator stays exhausted; call
keys()again for a fresh one. - Iterator helpers. Newer engines let you chain on the iterators directly, for example
map.values().filter(...).toArray(). These are recent, so check a compatibility table; the spread-to-array pattern works everywhere. - Printing.
console.log(map)shows the entries in most consoles, butJSON.stringify(map)gives{}.
Browser support
for...of, forEach(), keys(), values() and entries() on Map work in every current browser and in Node.js. Iterator helpers on the returned iterators are newer.
Related
- Map
- Map.prototype.size
- Array.from()
- Iterator helpers
- Lesson: Maps
- Lesson: for...of and for...in