0.4 Loops & Jump Statements (`break`, `continue`)
Loops allow you to repeat a block of code multiple times efficiently without writing repetitive code manually.
1. The Anatomy of a `for` Loop
A standard for loop consists of three parts separated by semicolons:
// (1) Initialization ; (2) Condition ; (3) Increment/Update
for (let i = 0; i < 5; i++) {
console.log("Iteration number:", i);
}
- Initialization:
let i = 0sets up a counter variable. - Condition:
i < 5checked before each loop iteration. - Increment:
i++increasesiby 1 after each loop body finishes.
2. `while` and `do...while` Loops
Use a while loop when you don't know in advance how many times to repeat:
let energy = 100;
while (energy > 0) {
console.log("Running... energy left:", energy);
energy -= 25; // Decrement energy towards 0
}
3. Controlling Loop Flow: `break` vs `continue`
break: Immediately halts and exits the entire loop.continue: Skips the rest of the current iteration and jumps straight to the next cycle.
for (let i = 1; i <= 5; i++) {
if (i === 3) continue; // Skip number 3
if (i === 5) break; // Stop loop at 5
console.log("Number:", i); // Output: 1, 2, 4
}
📌 KEY POINTS TO REMEMBER
- `break` vs `continue`:
breakdestroys the loop immediately.continueskips current step and moves to next step. - Preventing Infinite Loops: Always ensure the condition in a
whileloop will eventually becomefalse(e.g. updating the counter inside the loop body). - Zero-Indexing: Loops commonly start counting from
0(e.g.,let i = 0).
⚡ Interactive Visual: Loop Stepper & Jump Control
Run interactive loop simulations with break/continue:
Click a loop button above.