Pebellslearn by building
0%
RoadmapsMatrixCoursesSandboxSign in
Loops and Control Flow  ›  Lesson

The for...of Loop

for...of loop 10 minfor...of walks any iterable — arrays, strings, Maps, Sets — and hands you each VALUE directly, with no index and no counting, but it throws on a plain object, which has no iterator.

The for...of Loop

In short: for (const value of iterable) hands you each value directly, one at a time, with no index and no counting. It works on any iterable — arrays, strings, Maps, Sets — because each of those defines how to hand out its items in order. It does not work on a plain object, which has no built-in order to iterate, and throws a TypeError if you try.

A conveyor belt of three song titles; a hand labelled for (const song of list) reaches down and takes one VALUE at a time, with a note that each lap hands you the value itself, no index, no counting

Printing every song, no counting required

When you don't need the position, for...of is the cleanest way to visit every item:

javascript

Compare this with a for loop that needs songs[i] and an index variable you never actually use — for...of hands you the song directly.

Walking a string, and a Map's entries

for...of isn't just for arrays — it works on anything iterable:

javascript

A string hands out one character per lap. A Map hands out [key, value] pairs, which the loop destructures straight into title and count — no .get() calls needed.

The object that isn't iterable

The trap: a plain object looks like it should work, but doesn't.

javascript

Arrays, strings, Maps and Sets all define an iterator — a built-in way to hand out their contents in order. A plain object doesn't, so for...of has nothing to walk and throws a TypeError. To loop over an object's own properties, use for...in (next lesson) or Object.entries(song), which turns it into an iterable array of pairs.

Quick practice

quick drill

What does for (const x of [10, 20, 30]) { console.log(x); } print?

quick drill

What does for (const ch of "Go") { console.log(ch); } print?

quick drill

What happens when for...of runs on a plain object like { a: 1 }?

Practice — level up

0/1 solved

Write your answer, then compare it with a rubric and a model answer.

ExplainWhy does for...of reject a plain object?

for (const x of { title: "Blue Hour", plays: 12 }) { console.log(x); } throws TypeError: ... is not iterable. Explain why, and name two kinds of value it would work on instead.