for loops
This page needs a recent browser (with SharedArrayBuffer support). Please update Chrome, Edge, Firefox or Safari to the latest version.
Repeating with a for loop
- A loop runs the same block many times, so you don't repeat yourself.
for (let i = 1; i <= 5; i++) { ... }has three parts: starti = 1, testi <= 5, stepi++.
for (let i = 1; i <= 3; i++) {
console.log(i); // → 1, then 2, then 3
}
Build a running total
- Keep a variable outside the loop and add to it on every pass.
let total = 0;
for (let i = 1; i <= 10; i++) {
total = total + i;
}
console.log(total); // → 55
Explore
Trace the running total
A loop repeats its body. Step through the passes and watch total grow.
Watch out
i <= 5stops after 5;i < 5stops before 5. Picking the wrong one is the classic "off-by-one" bug.- Start the total at
0before the loop, not inside it.
Common mistakes
for (let i = 0; i < n; i++)runsntimes.- Declare the counter with
let, not without.
Now you try
- Use a
forloop. - Press Check answer to test it.
Use a for loop to log the numbers 1 to 5, one per line.
Click Run to see the output here.
Use a for loop to add up 1 to 10, then log the total (it is 55).
Click Run to see the output here.
Use a for loop to log the even numbers 2, 4, 6, one per line (step by 2 with i += 2).
Click Run to see the output here.