for and while loops
The for loop
The classic for loop has three parts in its brackets: a start, a condition, and a step.
JavaScript
for (let i = 1; i <= 5; i++) {
console.log("Step", i);
}let i = 1runs once at the start.i <= 5is checked before each round; the loop stops when it's false.i++(add one) runs after each round.
Counting down or in steps works the same way:
JavaScript
for (let i = 10; i > 0; i -= 3) {
console.log(i);
}Looping over an array by index
JavaScript
const colours = ["red", "green", "blue"];
for (let i = 0; i < colours.length; i++) {
console.log(i, colours[i]);
}(The next lesson shows the cleaner for...of loop for this.)
while
while repeats as long as its condition is true. Use it when you don't know how many rounds you'll need:
JavaScript
let balance = 1000;
let years = 0;
while (balance < 2000) {
balance *= 1.07;
years++;
}
console.log(`Doubled in ${years} years: ${balance.toFixed(2)}`);do...while
A do...while loop always runs at least once, because it checks the condition after the body:
JavaScript
let attempts = 0;
do {
attempts++;
console.log("Attempt", attempts);
} while (attempts < 3);break and continue
JavaScript
for (let n = 1; n <= 10; n++) {
if (n === 7) break; // stop the loop entirely
if (n % 2 === 0) continue; // skip even numbers
console.log(n);
}Finished this lesson?Mark it complete to earn +20 XP and move your progress on.