How to Iterate Over Map Elements in JavaScript

To iterate over map elements in JavaScript, you can use the “for…of loop” or “Map.forEach()” method.

Method 1: Iterating map with for..of loop

The for…of loop assigns the current iteration’s key and value to variables. The for…of loop might be your preferred approach if you have to use the break keyword to exit the loop prematurely.

Map also provides these three methods, which come in handy while iterating over a Map.

  1. map.keys(): It returns an iterable for keys.
  2. map.values(): It returns an iterable for values.
  3. map.entries(): It returns an iterable of key and value.

Example

const mainMap = new Map([
  ["key1", "value1"],
  ["key2", "value2"],
  ["key3", "value3"],
]);

for (const key of mainMap.keys()) {
  console.log(`Key: ${key}`);
}

for (const value of mainMap.values()) {
  console.log(`Value: ${value}`);
}

Output

Key: key1
Key: key2
Key: key3
Value: value1
Value: value2
Value: value3

Method 2: Using the forEach() Method

Use the Map.forEach() method to iterate through a Map object. The forEach() method takes a function invoked for each key-value pair in the Map in insertion order.

Example

const mainMap = new Map([
  ["key1", "value1"],
  ["key2", "value2"],
  ["key3", "value3"],
 ]);
 
 mainMap.forEach((value, key) => {
   console.log(`Key: ${key}, Value: ${value}`);
 });

Output

Key: key1, Value: value1
Key: key2, Value: value2
Key: key3, Value: value3

That’s it.