How to useforEach() loop in Javascript
The Map.forEach() method is used to loop over the map with the given function and execute the given function over each key-value pair.
Syntax:
myMap.forEach(callback, value, key, thisArg)
Example: Here we show the basic use of the Javascript Map.forEach() method.
// Creating a map using Map object
let newMap = new Map();
// Adding values to the map
newMap.set("Monday", 1);
newMap.set("Tuesday", 2);
newMap.set("Wednesday", 3);
// Logging map object to console
newMap.forEach((values, keys) => {
console.log(values, keys);
});
Output
1 Monday 2 Tuesday 3 Wednesday
How to iterate over Map elements in JavaScript ?
Map() is very useful in JavaScript it organises elements into key-value pairs. This method iterates over each element in an array and applies a callback function to it, allowing for modifications before returning the updated array.”
The Map() keyword is used to generate the object. The map() method loops through each object in the given array. The map() method combines with the entries() method to loop through the object and returns an array containing key-value pairs as its data.
Here we have two methods to iterate Map element in JavaScript:
Table of Content
- Using for…of loop
- Using forEach() loop
- Using Map.keys() method
Contact Us