Loops allow you to run the same block of code multiple times as long as a certain condition is met.
1. The for Loop
The most common loop. It uses a counter to keep track of how many times it has run. It has three parts:
Initialization: Where the counter starts (e.g.,
let i = 0).Condition: The loop runs as long as this is
true(e.g.,i < 5).Increment: How the counter changes after each round (e.g.,
i++adds 1).
2. The while Loop
A simpler loop that runs as long as a condition is true. It’s useful when you don’t know exactly how many times you need to loop.
3. break and continue
break: Stops the loop entirely and exits.continue: Skips the rest of the current round and jumps to the next one.
The Code Example
// 1. The Classic 'for' Loop
// (Start at 0; run while i is less than 5; add 1 each time)
for (let i = 0; i < 5; i++) {
console.log("Count is: " + i);
}
// 2. The 'while' Loop
let battery = 3;
while (battery > 0) {
console.log("Phone is on... Battery: " + battery + "%");
battery--; // Important: decrease so the loop eventually stops!
}
console.log("Phone shut down.");
// 3. Using 'continue' and 'break'
for (let j = 1; j <= 5; j++) {
if (j === 3) {
continue; // Skip the number 3
}
if (j === 5) {
break; // Stop the loop completely at 5
}
console.log("Number: " + j);
}
// Output: 1, 2, 4