Course contentsShow
← JavaScript
Lesson 1041 of 2,72324. Maps and SetsFree lesson

Iterating Over Maps

Using for...of with Maps to iterate in insertion order over entries.

Iterating Over Maps

What you'll learn: How to loop through a Map's entries using for...of while preserving insertion order.

Why Iterate Over Maps?

Unlike objects, Maps maintain the order in which you added key-value pairs. When you iterate over a Map, you'll always visit entries in the exact sequence they were inserted—no surprises, no alphabetical reordering.

Using for...of with Maps

The for...of loop works beautifully with Maps. By default, iterating directly over a Map gives you [key, value] pairs as arrays:

const menu = new Map();
menu.set('burger', 8);
menu.set('fries', 3);
menu.set('drink', 2);

for (const entry of menu) {
  console.log(entry);
  // ['burger', 8]
  // ['fries', 3]
  // ['drink', 2]
}

Destructuring for Cleaner Code

Since each entry is a two-element array, you can destructure it right in the loop:

for (const [item, price] of menu) {
  console.log(`${item}: $${price}`);
  // burger: $8
  // fries: $3
  // drink: $2
}

This pattern is common and readable—no need to access entry[0] and entry[1].

Why This Matters

Think of a Map like a guest list where arrival order matters. When you iterate, you call names in the exact order guests arrived—not alphabetically or randomly. This predictability makes Maps ideal when sequence matters.

Key Takeaway: Use for...of to iterate over Maps in insertion order; destructure [key, value] pairs directly in the loop for clean, readable code.