Movatterモバイル変換


[0]ホーム

URL:


  1. Web
  2. JavaScript
  3. Reference
  4. Standard built-in objects
  5. Map
  6. forEach()

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.

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

js
forEach(callbackFn)forEach(callbackFn, thisArg)

Parameters

callbackFn

A function to execute for each entry in the map. The function is called with the following arguments:

value

Value of each iteration.

key

Key of each iteration.

map

The map being iterated.

thisArgOptional

A value to use asthis when 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'svalue
  • the entry'skey
  • theMap object 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:

js
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

Browser compatibility

See also

Help improve MDN

Learn how to contribute

This page was last modified on byMDN contributors.


[8]ページ先頭

©2009-2025 Movatter.jp