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, zambiatek 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!



