JavaScript Set forEach() method - JavaScript Tutorial

JavaScript Set forEach() method

BLUF: This tutorial on JavaScript Set forEach() method provides an in-depth look at JavaScript's core features. It includes practical examples and code snippets to help you master modern JS development.
Key Discovery: JavaScript Set forEach() method

Understanding JavaScript Set forEach() method is crucial for building dynamic, interactive web applications. Explore the examples below to see it in action.

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:

Example

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

Example

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

Output

Fetching values :

key[jQuery] = jQuery

key[AngularJS] = AngularJS

key[Bootstrap] = Bootstrap

Input Required

This code uses input(). Please provide values below:

Logic Practice
Install Logic Practice
Add to home screen for a faster app-like experience