JavaScript Tutorial · Control Flow · Lesson 16 of 44

JavaScript Loops

Repeat code with for, while and do...while; control loops with break and continue.

for

The classic for loop has three parts: initialise; condition; update.

Example 1Try it yourself
for (let i = 1; i <= 5; i++) {
  console.log("Step", i);
}

Output

Step 1
Step 2
Step 3
Step 4
Step 5

while and do...while

while repeats as long as a condition is true. do...while always runs at least once:

Example 2Try it yourself
let n = 1;
while (n < 100) {
  n *= 3;
}
console.log(n);

let attempts = 0;
do {
  attempts++;
} while (attempts < 0);
console.log("attempts:", attempts);

Output

243
attempts: 1

break and continue

break exits the loop immediately; continue skips to the next iteration:

Example 3Try it yourself
for (let i = 1; i <= 10; i++) {
  if (i % 2 === 0) continue;  // skip even numbers
  if (i > 7) break;           // stop after 7
  console.log(i);
}

Output

1
3
5
7

Make sure every loop can end — an infinite loop freezes the page (on this site, the runner stops it after a few seconds).

Test yourself

Which loop always runs its body at least once?

  1. for
  2. while
  3. do...while
  4. for...of
Show answer

Answer: do...while