JavaScript Set forEach()
Syntax & Examples
Set.forEach() method
The forEach() method of the Set class in JavaScript executes a provided function once for each value present in the Set object, in insertion order.
Syntax of Set.forEach()
There are 2 variations for the syntax of Set.forEach() method. They are:
forEach(callbackFn)Parameters
| Parameter | Optional/Required | Description |
|---|---|---|
callbackFn | required | Function to execute for each element, taking three arguments: value, value again (for compatibility with Map), and the Set object. |
This method calls callbackFn once for each value present in the Set object, in insertion order.
Returns value of type undefined.
forEach(callbackFn, thisArg)Parameters
| Parameter | Optional/Required | Description |
|---|---|---|
callbackFn | required | Function to execute for each element, taking three arguments: value, value again (for compatibility with Map), and the Set object. |
thisArg | optional | Value to use as this when executing callbackFn. |
This method calls callbackFn once for each value present in the Set object, in insertion order. Uses thisArg as the this value for each invocation of callbackFn.
Returns value of type undefined.
✐ Examples
1 Using forEach() with a simple callback
In this example, we use the forEach() method to log each element of the Set to the console.
For example,
- We define a Set
mySetwith some values. - We use the
forEach()method with a callback function that logs each value to the console.
JavaScript Program
const mySet = new Set([1, 2, 3]);
mySet.forEach(value => console.log(value));Output
1 2 3
2 Using forEach() with a callback and thisArg
In this example, we use the forEach() method with a callback function that logs each value and the this value to the console. We pass an object as thisArg.
For example,
- We define a Set
mySetwith some values. - We define an object
thisArgwith a propertyprefix. - We use the
forEach()method with a callback function and passthisArgas the second argument. - The callback function logs the prefix and the value to the console.
JavaScript Program
const mySet = new Set(['a', 'b', 'c']);
const thisArg = { prefix: 'Value: ' };
mySet.forEach(function(value) {
console.log(this.prefix + value);
}, thisArg);Output
Value: a Value: b Value: c
3 Using forEach() to modify elements
In this example, we use the forEach() method to create a new array with modified elements from the Set.
For example,
- We define a Set
mySetwith some values. - We create an empty array
newArray. - We use the
forEach()method with a callback function that modifies each value and pushes it tonewArray. - We log
newArrayto the console.
JavaScript Program
const mySet = new Set([1, 2, 3]);
const newArray = [];
mySet.forEach(value => newArray.push(value * 2));
console.log(newArray);Output
[2, 4, 6]
Summary
In this JavaScript tutorial, we learned about forEach() method of Set: the syntax and few working examples with output and detailed explanation for each example.