Open In App

JavaScript Set forEach() Method

Last Updated : 12 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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)

Parameters:

  • Callback function: The function will be executed for each value and it takes three arguments.
  • Value, Key: Value should be the current element that is processed. The set does not contain the key, the value is passed in place of the key.
  • set: This is the object in which forEach() was applied. 
  • thisArg: Value used as this when the callback function is called.

Return Value:

  • This method returns undefined.

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

JavaScript
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. 

JavaScript
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 Browsers:

  • Chrome
  • Edge
  • Firefox
  • Opera
  • Safari

Next Article

Similar Reads