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

  • key and value: 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 Maps
let 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() method
evenNumbers.forEach((key, value)=>{
// log out each entry
console.log(key, value)
})
countries.forEach((key, value)=>{
// log out each entry
console.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.

Free Resources