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

The for Loop

Loops and Iterations 12 min

javascript / The for Loop

Explore each scene at your own pace.

01 · The for Loop

The for Loop

The for Loop

A for loop repeats a body while a condition remains truthy. Its initializer runs once, its condition is checked before each iteration, and its update runs after the body.

Track the index separately from the work done at that position.

See the mechanism

Walk through the modelThe for LoopAuthored snapshots of the example; use Run below to test the code.
i0
conditiontrue
item"Morning"
The condition is checked before reading index 0.
1 of 3

Follow one example

javascript

i starts at 0. Before each body run, i < titles.length decides whether that position is visited. After printing an item, i increases. When i becomes 3, the condition fails and the body does not read titles[3]. Replacing < with <= would visit an extra position.

Predict, change and check

Predict: How many lines will print for an empty titles array?

Test your explanation: Change < to <= and locate the extra undefined value. Restore <, then test an empty array and a one-item array.

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

Apply and distinguish

Check the boundary before repeating

A for loop's initializer runs once, its condition is tested before each iteration, and its update runs after the body unless control exits the loop. With an empty array, i < items.length is false immediately. Using <= reads one position beyond a dense array's last index.

State changes inside the loop can invalidate your assumptions about a changing collection's length or order. Prefer a stable input when transforming data, or document how removals affect the next index. Trace the first iteration, the last valid iteration and the stopping check instead of counting visible lines in the loop body.

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.