JavaScript Map forEach() method - JavaScript Tutorial

JavaScript Map forEach() method

BLUF: This tutorial on JavaScript Map 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 Map forEach() method

Understanding JavaScript Map 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 Map executes a designated function for each key/value pair within the Map object, performing the operation exactly once for every entry.

Syntax

The syntax for the forEach method is outlined as follows:

Example

mapObj.forEach(callback[, thisArg])

Parameter

callback - It represents the function to execute.

value - This signifies the value that is regarded as this when the callback function is executed.

JavaScript Map forEach method example

In this section, we will explore the forEach method by examining a range of examples.

Example 1

Let's examine an example that demonstrates how to retrieve values from a Map object.

Example

<script>

var map = new Map();

map.set(1,"jQuery");

map.set(2,"AngularJS");

map.set(3,"Bootstrap");

document.writeln("Fetching values :"+"<br>");

function display(values) 

{

document.writeln(values+"<br>");

}

map.forEach(display);

</script>

Output:

Output

jQuery

AngularJS

Bootstrap

Example 2

Let’s examine an example of how to retrieve both keys and values from a Map object.

Example

<script>

var map = new Map();

map.set(1,"jQuery");

map.set(2,"AngularJS");

map.set(3,"Bootstrap");

document.writeln("Fetching values and keys :"+"<br>");

function display(values,key) 

{

document.writeln(values+" "+key+"<br>");

}

map.forEach(display);

</script>

Output:

Output

Fetching values and keys :

jQuery 1

AngularJS 2

Bootstrap 3

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