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.
<script>
for (let i = 1; i <= 5; i++) {
document.write("Line " + i + "<br>");
}
</script>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.
<script>
let n = 1;
while (n <= 16) {
document.write(n + " ");
n = n * 2;
}
</script>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?
✍️ Practice
- Print the numbers 1 to 10, each on its own line.
- Print only the even numbers from 1 to 20 (hint:
i % 2 === 0). - Print the 7 times table using a loop.
🏠 Homework
- Use a loop to add up all numbers from 1 to 100 and print the total.