Skip to the workspace
Pebellslearn by building
Loops and Iterations  ›  Lesson

The for...of Loop

for...of loop 12 min

javascript / The for...of Loop

Explore each scene at your own pace.

01 · The for...of Loop

The for...of Loop

The for...of Loop

for...of visits values produced by an iterable. Arrays and strings are iterable; ordinary objects are not iterable by default.

Use it when you need each item rather than a manually managed index.

See the mechanism

Walk through the modelThe for...of LoopAuthored snapshots of the example; use Run below to test the code.
title"Morning"
The loop receives a value from the iterable.
1 of 3

Follow one example

javascript

Each iteration binds title to the next array value. No counter is necessary. A const loop binding can be new on each iteration without being reassigned within that iteration. For plain objects, choose an explicit collection such as Object.keys or Object.entries rather than assuming for...of can traverse the record itself.

Predict, change and check

Predict: Will title contain an index such as 0 or the text "Morning"?

Test your explanation: Add a third title, then try for...of over Object.keys({title: "Morning"}) to distinguish object keys from an array’s values.

The tasks below ask you to explain that result and apply the idea to different inputs.

Apply and distinguish

Values come from the iteration protocol

for...of reads values from an iterable, such as an array, string, Map or Set. A plain record is not automatically iterable; choose Object.entries when you intend to traverse its own enumerable string-keyed entries. String iteration yields code points, which are not universally the same as displayed grapheme clusters.

for...of is different from for...in: the latter enumerates string property keys and can include inherited properties. A break from a custom iterable can trigger its cleanup protocol. Do not treat iteration as a promise that the source is a dense array with numeric positions.

Check your understanding: State the input contract, identify the operation that changes the result, and give one boundary input that would distinguish the correct rule from the mistake described above.

Scene 1 of 2
Project context and further resources
Additional resources
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.