Map.prototype.forEach()
Baseline Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.
TheforEach() method ofMap instances executes a provided function once per each key/valuepair in this map, in insertion order.
In this article
Try it
function logMapElements(value, key, map) { console.log(`m[${key}] = ${value}`);}new Map([ ["foo", 3], ["bar", {}], ["baz", undefined],]).forEach(logMapElements);// Expected output: "m[foo] = 3"// Expected output: "m[bar] = [object Object]"// Expected output: "m[baz] = undefined"Syntax
forEach(callbackFn)forEach(callbackFn, thisArg)Parameters
callbackFnA function to execute for each entry in the map. The function is called with the following arguments:
thisArgOptionalA value to use as
thiswhen executingcallbackFn.
Return value
None (undefined).
Description
TheforEach method executes the providedcallback once for each key of themap which actually exist. It is not invoked for keys which have been deleted.However, it is executed for values which are present but have the valueundefined.
callback is invoked withthree arguments:
- the entry's
value - the entry's
key - the
Mapobject being traversed
If athisArg parameter is provided toforEach, it will be passed tocallback when invoked, for use as itsthis value. Otherwise, the valueundefined will be passed for use as itsthis value. Thethis valueultimately observable bycallback is determined according tothe usual rules for determining thethis seen by a function.
Each value is visited once, except in the case when it was deleted and re-addedbeforeforEach has finished.callback is not invoked for values deletedbefore being visited. New values added beforeforEach has finished will bevisited.
Examples
>Printing the contents of a Map object
The following code logs a line for each element in aMap object:
function logMapElements(value, key, map) { console.log(`map.get('${key}') = ${value}`);}new Map([ ["foo", 3], ["bar", {}], ["baz", undefined],]).forEach(logMapElements);// Logs:// "map.get('foo') = 3"// "map.get('bar') = [object Object]"// "map.get('baz') = undefined"Specifications
| Specification |
|---|
| ECMAScript® 2026 Language Specification> # sec-map.prototype.foreach> |