Thursday, December 18, 2025
HomeLanguagesJavascriptJavaScript Set forEach() Method

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:

  • 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 Browser:

  • Chrome 38
  • Edge 12
  • Firefox 25
  • Opera 25
  • Safari 8
Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!
Dominic
Dominichttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Dominic
32455 POSTS0 COMMENTS
Milvus
108 POSTS0 COMMENTS
Nango Kala
6823 POSTS0 COMMENTS
Nicole Veronica
11957 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12034 POSTS0 COMMENTS
Shaida Kate Naidoo
6957 POSTS0 COMMENTS
Ted Musemwa
7203 POSTS0 COMMENTS
Thapelo Manthata
6909 POSTS0 COMMENTS
Umr Jansen
6890 POSTS0 COMMENTS