Movatterモバイル変換


[0]ホーム

URL:


MDN Web Docs

Set.prototype.forEach()

BaselineWidely available

TheforEach() method ofSet instances executes a provided function oncefor each value in this set, in insertion order.

Try it

function logSetElements(value1, value2, set) {  console.log(`s[${value1}] = ${value2}`);}new Set(["foo", "bar", undefined]).forEach(logSetElements);// Expected output: "s[foo] = foo"// Expected output: "s[bar] = bar"// Expected output: "s[undefined] = undefined"

Syntax

js
forEach(callbackFn)forEach(callbackFn, thisArg)

Parameters

callback

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

value

Value of each iteration.

key

Key of each iteration. This is always the same asvalue.

set

The set being iterated.

thisArgOptional

A value to use asthis when executingcallbackFn.

Return value

None (undefined).

Description

TheforEach() method executes the providedcallback once for each value which actually exists in theSet object. It is not invoked for values which have been deleted. However,it is executed for values which are present but have the valueundefined.

callback is invoked withthree arguments:

  • theelement value
  • theelement key
  • theSet object being traversed

There are no keys inSet objects, however, so the first two arguments arebothvalues contained in theSet. This is to make itconsistent with otherforEach() methods forMap andArray.

If athisArg parameter is provided toforEach(),it will be passed tocallback when invoked, for use as itsthis value. Otherwise, the valueundefined will be passed foruse as itsthis value. Thethis value ultimately 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-added beforeforEach() has finished.callback is not invoked forvalues deleted before being visited. New values added beforeforEach() hasfinished will be visited.

forEach() executes thecallback function once foreach element in theSet object; it does not return a value.

Examples

Logging the contents of a Set object

The following code logs a line for each element in aSet object:

js
function logSetElements(value1, value2, set) {  console.log(`s[${value1}] = ${value2}`);}new Set(["foo", "bar", undefined]).forEach(logSetElements);// Logs:// "s[foo] = foo"// "s[bar] = bar"// "s[undefined] = undefined"

Specifications

Specification
ECMAScript® 2026 Language Specification
# sec-set.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