LoopsCore· 40 min read

Loops: for & while

Repeat work without repeating yourself. Loops are how computers handle thousands of items effortlessly.

What you will learn

  • Write a for loop
  • Write a while loop
  • Use break and continue

The for loop

A for loop has three parts: a start, a condition to keep going, and a step each time.

for (start; condition; step)
<script>
  for (let i = 1; i <= 5; i++) {
    document.write("Line " + i + "<br>");
  }
</script>
Live preview

Read it as: start i at 1; keep looping while i <= 5; add 1 to i each time. So the body runs with i being 1, then 2, 3, 4, 5 — five times — and stops when i reaches 6 (because 6 is no longer ≤ 5).

Note: Output: Line 1 Line 2 Line 3 Line 4 Line 5

The while loop

A while loop repeats as long as a condition is true. Use it when you do not know the count in advance.

Doubling with while
<script>
  let n = 1;
  while (n <= 16) {
    document.write(n + " ");
    n = n * 2;
  }
</script>
Live preview

n starts at 1. Each turn it prints n then doubles it (n = n * 2): 1 → 2 → 4 → 8 → 16. After printing 16 it doubles to 32, which fails the n <= 16 test, so the loop ends. Notice the loop runs an unknown number of times — we just keep going while the condition holds.

Note: Output: 1 2 4 8 16

Watch out: Always make sure the loop will end — the condition must eventually become false. A loop that never stops (an infinite loop) freezes the page.

break and continue

  • break — exit the loop immediately.
  • continue — skip to the next turn of the loop.

Q. In for (let i = 0; i < 10; i++), what does i++ do?

Answer: i++ is the step — it adds 1 to i after each iteration, eventually making the condition false to end the loop.

✍️ Practice

  1. Print the numbers 1 to 10, each on its own line.
  2. Print only the even numbers from 1 to 20 (hint: i % 2 === 0).
  3. Print the 7 times table using a loop.

🏠 Homework

  1. Use a loop to add up all numbers from 1 to 100 and print the total.
Want to learn this with a mentor?

CodingClave runs guided, project-based training (28-day, 45-day & 6-month batches).

Explore Training →