Loops
for loop
A loop with a counter: repeats code while a condition holds.
Why it exists
Computers are valuable because they repeat actions tirelessly: process a thousand orders, draw a hundred cells, check every letter of a password. You can't copy code a thousand times — you need a loop. The classic for gives full control: where to start, where to stop and how big each step is. That's why it's the choice when the step's number matters: going backwards, every other item, two arrays at once.
Where it's used
- Going backwards: reverse a string, show the newest messages first.
- When you need the item's number: "1. Milk, 2. Bread" in a shopping list.
- When the step isn't 1: every second item, pages of 10.
- Repeat N times: draw 5 rating stars, retry a request 3 times.
Syntax
for (let i = start; condition; step) {
// loop body
}Examples
const seen = [];
for (let i = 0; i < 3; i++) {
seen.push(i);
}
seen; // → [0, 1, 2]
const back = [];
for (let i = 3; i > 0; i--) {
back.push(i);
}
back; // → [3, 2, 1]const items = ["Milk", "Bread"];
const lines = [];
for (let i = 0; i < items.length; i++) {
lines.push(i + 1 + ". " + items[i]);
}
lines; // → ["1. Milk", "2. Bread"]const evens = [];
for (let i = 0; i <= 10; i += 2) {
evens.push(i);
}
evens; // → [0, 2, 4, 6, 8, 10]let stars = "";
for (let i = 0; i < 5; i++) {
stars += i < 4 ? "★" : "☆";
}
stars; // → "★★★★☆"Results after // → aren't just written down — an automatic check runs and verifies them before every site update.
Why it works this way
The parentheses hold three parts separated by ;. The start (let i = 0) runs once before the loop. The condition (i < 3) is checked before every step: if it's false, the loop ends. The step (i++) runs after each pass of the body.
The order: start → condition → body → step → condition → body → step… If the condition is false from the start, the body never runs.
The counter is declared with let because it changes. It's visible only inside the loop.
For arrays you usually go from 0 to length - 1: the condition is i < arr.length (strictly less!), because indexes start at zero.
Traps
How it differs from…
for...ofloopIf you don't need the number, for...of is shorter and can't be off by one: it hands you each item itself.
When to pick something else
Practice
Lessons where this appears
- Byte's sock empireTale · Chapter 5 · Arrays and loops
- The Infinite LoopBoss · Chapter 5 · Arrays and loops
- Why map and not a loop?Why? · Chapter 10 · map, filter, reduce
- A shift on the conveyorWorkshop · Chapter 10 · map, filter, reduce
- Why didn't the variable disappear?Why? · Chapter 12 · Scope and closures
- The case of the silent buttonsInvestigation · Chapter 12 · Scope and closures