The forEach method of the JavaScript Set executes a provided function for each element present in the Set object, processing them in the order they were added.
In contrast to Map, the Set object does not utilize an external key. To ensure the uniqueness of values, it relies on a key internally. Consequently, Set treats the value of each element as its corresponding key.
Syntax
The syntax for the forEach method is as follows:
setObj.forEach(function callback(value1, value2, Set) {
//your iterator
}[, thisArg])
Parameter
callback - It represents the function to execute.
value1, value2 - The value1 signifies the identifier of the element, while value2 denotes the corresponding value. Both parameters hold identical values.
set - It represents the current Set object.
thisArg - It signifies the value that is utilized as this during the execution of the callback function.
JavaScript Set forEach method example
Let's see a simple example of forEach method
<script>
var set = new Set(["jQuery","AngularJS","Bootstrap"]);
document.writeln("Fetching values :"+"<br>");
set.forEach(function display(value1,value2,set)
{
document.writeln('key[' + value1 + '] = ' + value2+"<br>");
})
</script>
Output:
Fetching values :
key[jQuery] = jQuery
key[AngularJS] = AngularJS
key[Bootstrap] = Bootstrap