Set.prototype.forEach()
BaselineWidely 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 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
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:
thisArg
OptionalA value to use as
this
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
- the
Set
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:
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 |