Open In App

JavaScript Set forEach() Method

The set.forEach() method is used to execute the function which is taken as a parameter and applied for each value in the set, in insertion order.

Syntax:



forEach(function(value, key, set) { 
    /* ... */ 
}, thisArg)

Parameter:

Return Value: This method returns undefined.



Example 1: In this example, we will see the use of the forEach() method.




function setValue(value1, value2, mySet) {
    console.log(`s[${value1}] = ${value2}`);
}
 
new Set(['Chicago', 'California', undefined])
    .forEach(setValue);

Output:

s[Chicago] = Chicago
s[California] = California
s[undefined] = undefined  

Example 2: In this example, we will see the use of the forEach() method to display the value of Set. 




let fruits = new Set();
fruits.add("Mango");
fruits.add("Banana");
fruits.add("Papaya");
fruits.add("Grapes");
 
function display(i, set) {
    console.log(i);
}
fruits.forEach(display);

Output:

Mango
Banana
Papaya
Grapes

We have a complete list of Javascript Set methods, to check those please go through the Sets in JavaScript article.

Supported Browser:

Article Tags :