0
0
JavascriptHow-ToBeginner · 3 min read

How to Iterate Over Map in JavaScript: Simple Guide

To iterate over a Map in JavaScript, use a for...of loop with map.entries() or map.forEach(). These methods let you access each key-value pair easily.
📐

Syntax

You can iterate over a Map using these common patterns:

  • for (const [key, value] of map.entries()) { ... } - loops over each key-value pair.
  • map.forEach((value, key) => { ... }) - calls a function for each pair.
  • for (const key of map.keys()) { ... } - loops over keys only.
  • for (const value of map.values()) { ... } - loops over values only.
javascript
for (const [key, value] of map.entries()) {
  // use key and value
}

map.forEach((value, key) => {
  // use key and value
});

for (const key of map.keys()) {
  // use key
}

for (const value of map.values()) {
  // use value
}
💻

Example

This example shows how to create a Map and iterate over it using for...of and forEach to print keys and values.

javascript
const map = new Map();
map.set('apple', 1);
map.set('banana', 2);
map.set('cherry', 3);

console.log('Using for...of loop:');
for (const [key, value] of map.entries()) {
  console.log(`${key} = ${value}`);
}

console.log('Using forEach method:');
map.forEach((value, key) => {
  console.log(`${key} => ${value}`);
});
Output
Using for...of loop: apple = 1 banana = 2 cherry = 3 Using forEach method: apple => 1 banana => 2 cherry => 3
⚠️

Common Pitfalls

Common mistakes when iterating over a Map include:

  • Using for...in which is for objects, not Map.
  • Confusing the order of parameters in forEach callback; it is (value, key), not (key, value).
  • Trying to access map[i] like an array, which does not work.
javascript
const map = new Map([['a', 1], ['b', 2]]);

// Wrong: for...in does not work on Map
for (const key in map) {
  console.log(key); // No output
}

// Wrong: forEach parameters order
map.forEach((key, value) => {
  console.log(key, value); // key is actually value, value is key
});

// Right way:
map.forEach((value, key) => {
  console.log(key, value); // Correct order
});
Output
a 1 b 2 a 1 b 2
📊

Quick Reference

Summary of ways to iterate over a Map:

MethodDescriptionExample
for...of with entries()Iterate over key-value pairsfor (const [k,v] of map.entries()) { ... }
forEach()Call function for each pairmap.forEach((v,k) => { ... })
for...of with keys()Iterate over keys onlyfor (const k of map.keys()) { ... }
for...of with values()Iterate over values onlyfor (const v of map.values()) { ... }

Key Takeaways

Use for...of with map.entries() or map.forEach() to iterate over Map key-value pairs.
Remember forEach callback parameters order is (value, key), not (key, value).
Avoid using for...in or array-style indexing with Map objects.
You can also iterate keys or values separately with map.keys() or map.values().