JavaScript - Set.forEach() Method
The Set.forEach() method in JavaScript accepts a callback function as a parameter and executes it once for each element in the set, in insertion order.
Syntax
Following is the syntax of JavaScript Set.forEach() method −
forEach(callbackFn, thisArg)
Parameters
This method accepts only two parameters. The same is described below −
- callbackFn − This is the function to execute for each element in the set, and it takes three parameters:
- value − The current element being processed.
- key − Key of each iteration. This is always the same as value.
- set − The set being iterated.
- thisArg (optional) − Value to use as this when executing the callback.
Return value
This method returns none (undefined).
Examples of JavaScript Set.forEach() Method
Following are demonstrates the basic usage of Set.forEach() method −
Example 1
In the following example, we are using the JavaScript Set.forEach() method to iterate through each element in the "mySet" Set and prints them −
<html>
<body>
<script>
const mySet = new Set([1, 2, 3, 4]);
mySet.forEach((value) => {
document.write(value);
});
</script>
</body>
</html>
After executing the program, we can see that all the elements present in the set got printed.
Example 2
Here, the forEach() method iterates over elements in "mySet" set, and for each element, it multiplies it by 2, and stores the result in a new set named "newArray" −
<html>
<body>
<script>
const mySet = new Set([1, 2, 3]);
const newArray = new Set();
mySet.forEach((value) => {
newArray.add(value * 2);
});
const resultArray = Array.from(newArray);
document.write(resultArray);
</script>
</body>
</html>
If we execute the program, we can see that all the elements got multiplied by 2 and stored in a new set.