11. JavaScript Loops
What you will learn
- How to repeat code with
forandwhile - The
for...ofloop for lists - How to use
breakandcontinue - How to avoid endless loops
Why loops?
A loop runs the same code several times. Instead of writing ten nearly identical lines, you write one and repeat it.
The for loop
Syntax
for (start; condition; step) {
// code to repeat
}
- start runs once before the loop begins (usually
let i = 0). - condition is checked before each round. The loop continues while it is true.
- step runs after each round (usually
i++).
Example
<p id="demo"></p>
<script>
let text = "";
for (let i = 1; i <= 5; i++) {
text += "Round " + i + "<br>";
}
document.getElementById("demo").innerHTML = text;
</script>
Output (after the script runs)
Round 1
Round 2
Round 3
Round 4
Round 5
A multiplication table
Example
<p id="demo"></p>
<script>
const n = 7;
let lines = "";
for (let i = 1; i <= 5; i++) {
lines += n + " x " + i + " = " + (n * i) + "<br>";
}
document.getElementById("demo").innerHTML = lines;
</script>
Output (after the script runs)
7 x 1 = 7
7 x 2 = 14
7 x 3 = 21
7 x 4 = 28
7 x 5 = 35
The while loop
while repeats as long as a condition stays true. Use it when you do not know in advance how many rounds you need.
Example
<p id="demo"></p>
<script>
let money = 100;
let years = 0;
while (money < 200) {
money = money * 1.1; // grows 10% a year
years++;
}
document.getElementById("demo").textContent =
"It takes " + years + " years to double.";
</script>
Output (after the script runs)
It takes 8 years to double.
A do...while loop is similar but always runs at least once, because it checks the condition at the end.
Endless loops: if the condition never becomes false, the loop never ends and the page freezes. Always make sure something inside the loop changes the condition. In the Try it Yourself editor, close the editor if it freezes.
Looping through a list: for…of
Example
<p id="demo"></p>
<script>
const courses = ["HTML", "CSS", "JavaScript"];
let out = "";
for (const course of courses) {
out += "I am learning " + course + "<br>";
}
document.getElementById("demo").innerHTML = out;
</script>
Output (after the script runs)
I am learning HTML
I am learning CSS
I am learning JavaScript
for...of gives you each value directly. Arrays are covered fully in a later lesson. You can also loop over the characters of a string the same way.
break and continue
breakleaves the loop completely.continueskips the rest of this round and starts the next.
Example
<p id="demo"></p>
<script>
let out = "";
for (let i = 1; i <= 10; i++) {
if (i % 2 === 0) { continue; } // skip even numbers
if (i > 7) { break; } // stop after 7
out += i + " ";
}
document.getElementById("demo").textContent = "Odd numbers up to 7: " + out;
</script>
Output (after the script runs)
Odd numbers up to 7: 1 3 5 7
Nested loops
A loop can sit inside another. The inner loop completes fully for every round of the outer loop.
Example
<p id="demo"></p>
<script>
let grid = "";
for (let row = 1; row <= 3; row++) {
for (let col = 1; col <= 4; col++) {
grid += "*";
}
grid += "<br>";
}
document.getElementById("demo").innerHTML = grid;
</script>
Output (after the script runs)
****
****
****
Common mistakes
- Endless loops: forgetting
i++or writing a condition that stays true. - Off-by-one errors:
<versus<=. - Using
varfor the counter, which leaks outside the loop. Uselet. - Changing the list while looping through it.
Exercise
Use a loop to add up the numbers from 1 to 10 and show Total: 55.
Show solution
<p id="demo"></p>
<script>
let total = 0;
for (let i = 1; i <= 10; i++) {
total += i;
}
document.getElementById("demo").textContent = "Total: " + total;
</script>
Knowledge check
1. What are the three parts of a for loop header?
Start, condition, and step.
2. What does continue do?
It skips to the next round of the loop.
3. What causes an endless loop?
A condition that never becomes false.
Summary
forsuits a known number of rounds,whilean unknown number, andfor...oflists.breakexits andcontinueskips a round.- Always make sure the loop can finish.