Skip to content
Tutorials Center
My learning

Topics

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.

JavaScript
for (const [key, value] of map) { /* ... */ }
map.forEach((value, key) => { /* ... */ });

Try it

JS Four ways to loop

Press Run (or Ctrl + Enter) to see the console output here.

No output.

JS Transforming and sorting

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Syntax

JavaScript
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() match Array.prototype.forEach(). The callback gets (value, key, map), so (value, key) is the reverse of the pairs you get from for...of.
  • for...of supports break, continue and await; forEach() does not. Prefer for...of when 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() or filter(). Convert to an array, transform, and pass the result back into new 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, but JSON.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.