Course contentsShow
← JavaScript
Lesson 353 of 2,72310. LoopsFree lesson

For...of with Sets and Maps

Use for...of to loop through Set values and Map entries efficiently.

For...of with Sets and Maps

You'll learn: How to use for...of loops to efficiently iterate through Set values and Map entries.


The Core Idea

You already know for...of works beautifully with arrays and strings. It also shines with Sets and Maps—two iterable data structures. For Sets, you get each value directly. For Maps, you get key-value pairs as arrays, making it easy to destructure them.


Looping Through a Set

A Set is a collection of unique values. for...of gives you each value one at a time:

const colors = new Set(['red', 'green', 'blue']);

for (const color of colors) {
  console.log(color);
}
// Logs: red, green, blue

No indexes, no fuss—just the values in insertion order.


Looping Through a Map

A Map stores key-value pairs. When you use for...of on a Map, each iteration gives you a two-element array: [key, value]. You can destructure it immediately:

const scores = new Map([
  ['Alice', 95],
  ['Bob', 87],
  ['Charlie', 92]
]);

for (const [name, score] of scores) {
  console.log(name + ' scored ' + score);
}
// Logs: Alice scored 95, Bob scored 87, Charlie scored 92

Without destructuring, you'd get arrays like ['Alice', 95], but destructuring makes your code cleaner.


Why This Matters

for...of respects the natural iteration order of Sets and Maps. It's more readable than manual iterator manipulation and avoids the awkwardness of traditional for loops when you don't have numeric indexes.

Key Takeaway:
Use for...of with Sets to loop through unique values directly, and with Maps to easily access key-value pairs using destructuring—it's the cleanest way to iterate these collections.