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
0true"Morning"Follow one example
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.