- JavaScript Map forEach() Method
- Syntax
- Parameters
- Return Value
- Example 1: Basic use of JavaScript Map.forEach() Method
- Example 2: Printing the contents of Map Object
- Browsers Supported
- Map.prototype.forEach()
- Try it
- Syntax
- Parameters
- Return value
- Description
- Examples
- Printing the contents of a Map object
- Specifications
- Browser compatibility
- See also
- Found a content problem with this page?
- How to Use forEach() to Iterate Through a JavaScript Map
- Map#entries()
- Map#keys() and Map#values()
- More Fundamentals Tutorials
- Javascript map for each
- # Table of Contents
- # Iterate through a Map object in JavaScript
- # Iterate through a Map object using a for. of loop
- # Iterating over the Keys or Values of a Map object
- # Iterate over a Map in Reverse Order
- # Additional Resources
JavaScript Map forEach() Method
JavaScript Map forEach() function is “used to execute a given function once per each key/value pair in the Map object, in insertion order”.
Syntax
map.forEach(callback, value, key, thisArg)
Parameters
- callback: This is a callback function that executes each function call.
- value: This is the value for each iteration.
- key: This is the key to reaching iteration.
- thisArg: This is the value to use as this when executing callback.
Return Value
The forEach() function returns the undefined value.
Example 1: Basic use of JavaScript Map.forEach() Method
let myMap = new Map(); myMap.set("a", 1); myMap.set("b", 2); myMap.set("c", 3); function showPair(value, key) console.log(`key: $, value: $`); > myMap.forEach(showPair);
key: a, value: 1 key: b, value: 2 key: c, value: 3
Example 2: Printing the contents of Map Object
let mp = new Map(); // Adding values to the map mp.set("First", "Krunal"); mp.set("Second", "Ankit"); mp.set("Third", "Rushabh"); mp.set("Fourth", "Dhaval"); mp.set("Fifth", "Niva"); mp.forEach((values, keys) => console.log("values: ", values + ", keys: ", keys + "\n") >);
values: Krunal, keys: First values: Ankit, keys: Second values: Rushabh, keys: Third values: Dhaval, keys: Fourth values: Niva, keys: Fifth
In this example, we created a Map and then inserted the values in the map using the set() method.
Then using the forEach() method, we iterate the map and log the key and value individually.
Browsers Supported
- Google Chrome
- Microsoft Edge
- Mozilla Firefox
- Internet Explorer
- Safari
- Opera
Map.prototype.forEach()
The forEach() method executes a provided function once per each key/value pair in the Map object, in insertion order.
Try it
Syntax
forEach(callbackFn) forEach(callbackFn, thisArg)
Parameters
A function to execute for each entry in the map. The function is called with the following arguments:
A value to use as this when executing callbackFn .
Return value
Description
The forEach method executes the provided callback once for each key of the map which actually exist. It is not invoked for keys which have been deleted. However, it is executed for values which are present but have the value undefined .
callback is invoked with three arguments:
- the entry’s value
- the entry’s key
- the Map object being traversed
If a thisArg parameter is provided to forEach , it will be passed to callback when invoked, for use as its this value. Otherwise, the value undefined will be passed for use as its this value. The this value ultimately observable by callback is determined according to the usual rules for determining the this seen by a function.
Each value is visited once, except in the case when it was deleted and re-added before forEach has finished. callback is not invoked for values deleted before being visited. New values added before forEach has finished will be visited.
Examples
Printing the contents of a Map object
The following code logs a line for each element in an Map object:
function logMapElements(value, key, map) console.log(`map.get('$key>') = $value>`); > new Map([ ["foo", 3], ["bar", >], ["baz", undefined], ]).forEach(logMapElements); // Logs: // "map.get('foo') = 3" // "map.get('bar') = [object Object]" // "map.get('baz') = undefined"
Specifications
Browser compatibility
BCD tables only load in the browser
See also
Found a content problem with this page?
This page was last modified on Apr 12, 2023 by MDN contributors.
Your blueprint for a better internet.
How to Use forEach() to Iterate Through a JavaScript Map
JavaScript’s Map object has a handy function, forEach() , which operates similarly to arrays’ forEach() function. JavaScript calls the forEach() callback with 3 parameters: the value, the key, and the map itself.
const map = new Map(); map.set('greeting', 'Hello'); map.set('name', 'John'); map.forEach((value, key, map) => < // Prints "greeting Hello" followed by "name John" console.log(value, key); >);
Map#entries()
JavaScript maps don’t have chainable helpers like filter() or map() for arrays. If you want to use filter() with a map, you should use Map#entries() to first convert the map to an iterator, and then use the the spread operator or the Array.from() function to convert the iterator to an array.
const map = new Map(); map.set('greeting', 'Hello'); map.set('name', 'John'); [. map.entries()]; // [['greeting', 'Hello'], ['name', 'John']] Array.from(map.entries()); // [['greeting', 'Hello'], ['name', 'John']] // Equivalent since `entries()` is the default iterator [. map]; // [['greeting', 'Hello'], ['name', 'John']] // First convert map into an array of entries, then you can use `filter()` [. map.entries()].filter((Javascript map for each) => value.length > 4); // [['greeting', 'Hello']]
Map#keys() and Map#values()
If you only need the keys or the values of the Map , you can use Map#keys() or Map#values() . Map#keys() returns an iterator over the map’s keys, and Map#values() returns an iterator over the map’s values. Make sure you convert the iterator to an array using the spread operator or Array.from() if you want to use filter() or map() !
const map = new Map(); map.set('greeting', 'Hello'); map.set('name', 'John'); Array.from(map.keys()); // ['greeting', 'name'] Array.from(map.values()); // ['Hello', 'John']
More Fundamentals Tutorials
Javascript map for each
Last updated: Jan 6, 2023
Reading time · 4 min
# Table of Contents
# Iterate through a Map object in JavaScript
Use the Map.forEach() method to iterate through a Map object.
The forEach method takes a function that gets invoked for each key-value pair in the Map in insertion order.
Copied!const map1 = new Map([ ['country', 'Chile'], ['age', 30], ]); map1.set('name', 'bobby hadz'); map1.forEach((value, key) => // Chile country // 30 age // bobby hadz name console.log(value, key); >);
The function we passed to the Map.forEach method gets called for each key-value pair in the Map object.
The function gets passed 3 arguments on each iteration:
- the value of the current iteration
- the key of the current iteration
- the Map object that is being iterated
The Map.forEach() method returns undefined .
# Iterate through a Map object using a for. of loop
Alternatively, you can use a for. of loop.
The for. of loop assigns the key and the value of the current iteration to variables.
Copied!const map1 = new Map([ ['country', 'Chile'], ['age', 30], ]); map1.set('name', 'bobby hadz'); for (const [key, value] of map1) // country Chile // age 30 // name bobby hadz console.log(key, value); >
The for. of statement is used to loop over iterable objects like arrays, strings, Map , Set and NodeList objects and generators .
We used destructuring assignment to assign the key and value variables.
Copied!const [key, value] = ['country', 'Chile']; console.log(key); // 👉️ country console.log(value); // 👉️ Chile
The for. of loop might be your preferred approach if you have to use the break keyword to exit the loop prematurely.
Using the break keyword is not supported in the forEach() method.
# Iterating over the Keys or Values of a Map object
This is a two-step process:
- Use the Map.keys() method to get an iterator object of the Map’s keys.
- Use the Map.values() method to get an iterator object of the Map’s values.
- Use a for. of loop to iterate over the keys or values.
Copied!const map1 = new Map([ ['country', 'Chile'], ['age', 30], ]); map1.set('name', 'bobby hadz'); for (const key of map1.keys()) // country // age // name console.log(key); >
If you need to iterate over the Map object’s values, use the Map.values() method.
Copied!const map1 = new Map([ ['country', 'Chile'], ['age', 30], ['name', 'bobby hadz'], ]); for (const key of map1.values()) // Chile // 30 // bobby hadz console.log(key); >
The Map.keys method returns an iterator object of the Map’s keys.
Copied!const map1 = new Map([ ['country', 'Chile'], ['age', 30], ['name', 'bobby hadz'], ]); // 👇️ [Map Iterator] console.log(map1.keys()); // 👇️ [Map Iterator] console.log(map1.values());
The Map.values() method returns an iterator object of the Map’s values.
The for. of loop is useful when you need to exit the loop prematurely if a certain condition is met.
Copied!const map1 = new Map([ ['country', 'Chile'], ['age', 30], ['name', 'bobby hadz'], ]); for (const value of map1.values()) console.log(value); if (value === 'Chile') break; > >
If the condition in the if statement is met, the break statement exits the for. of loop.
Note that the return values of the Map.keys() and Map.values() methods are not arrays, they are iterator objects.
You can use the Array.from method if you want to convert the Map’s values or keys to an array, e.g. to be able to use the forEach method.
Copied!const map1 = new Map([ ['country', 'Chile'], ['age', 30], ]); // 👇️️ ['country, 'age'] const keys = Array.from(map1.keys()); // 👇️️ ['Chile', 30] const values = Array.from(map1.values());
You can also use the spread syntax (. ) to unpack the values from the iterator object into an array.
Copied!const map1 = new Map([ ['country', 'Chile'], ['age', 30], ]); const keys = [. map1.keys()]; // 👉️ ['country, 'age'] const values = [. map1.values()]; // 👉️ ['Chile', 30]
The last 2 examples achieve the same result. They both convert the iterator objects to arrays.
# Iterate over a Map in Reverse Order
To iterate over a Map in reverse order:
- Use the Array.from() method to convert the Map to an array.
- Use the reverse() method to reverse the array.
- Use the forEach() method to iterate over the reversed array.
Copied!const map1 = new Map([ ['one', 1], ['two', 2], ]); // 👇️ [['two', 2], ['one', 1]] const reversedArr = Array.from(map1).reverse(); reversedArr.forEach(([key, value]) => console.log(key, value); // 👉️ two 2, one 1 >);
The first step is to convert the Map to an array.
Copied!const map1 = new Map([ ['one', 1], ['two', 2], ]); // 👇️ [['one', 1], ['two', 2]] const arr = Array.from(map1);
We used the Array.reverse() method to reverse the array.
Copied!const map1 = new Map([ ['one', 1], ['two', 2], ]); // 👇️ [['one', 1], ['two', 2]] const arr = Array.from(map1); // 👇️ [['two', 2], ['one', 1]] const reversed = arr.reverse();
You can use the Array.forEach method to iterate over the reversed array.
The function we passed to the forEach method gets called with each element of the array.
We used destructuring assignment to assign the key and value variables.
Copied!const [key, value] = ['one', 1]; console.log(key); // 👉️ "one" console.log(value); // 👉️ 1
Copied!const map1 = new Map([ ['one', 1], ['two', 2], ]); // 👇️ [['two', 2], ['one', 1]] const reversedArr = [. map1].reverse(); reversedArr.forEach(([key, value]) => console.log(key, value); // 👉️ two 2, one 1 >);
This code sample achieves the same result, however, this time we used the spread syntax (. ) to unpack the key-value pairs of the Map into an array.
In some very rare cases, the spread syntax (. ) doesn’t play nice when using TypeScript. This issue doesn’t occur when using Array.from .
# Additional Resources
You can learn more about the related topics by checking out the following tutorials:
I wrote a book in which I share everything I know about how to become a better, more efficient programmer.