CodeMIRAI
0 XP

for and while loops

2 min read 6 runnable examples Quiz included

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);
}
  1. let i = 1 runs once at the start.
  2. i <= 5 is checked before each round; the loop stops when it's false.
  3. 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.