What is the map.forEach() method in TypeScript?
Overview
A map is a data structure used to store key-value entries. We can easily invoke the forEach() method to iterate over the key-value pair of the map.
Syntax
map.forEach((key, value) =>{// iterate over key/value pairs})
forEach() method of a Map in TypeScript
Parameters
keyandvalue: These are the key-value pairs of the map we want to iterate over.
Return value
This method returns a loop.
Code example
Let's look at the code below:
// create some Mapslet evenNumbers = new Map<string, number>([["two", 2], ["four", 4], ["eight", 8]])let countries = new Map<string, string>([["NG", "Nigeria"], ["BR", "Brazil"], ["IN", "India"]])// invoke the forEach() methodevenNumbers.forEach((key, value)=>{// log out each entryconsole.log(key, value)})countries.forEach((key, value)=>{// log out each entryconsole.log(key, value)})
Code explanation
- Lines 2 and 3: We create some TypeScript maps.
- Lines 6 and 10: We use the
forEach()method to loop through the maps and print each entry of the maps to the console.