Repeating with loops
Run the same code many times without writing it many times.
Your JavaScript code runs inside your browser tab. Nothing to install.
The for loop
A for loop repeats a block of code. It has three parts in its brackets: where to start, when to keep going, and what to change each time.
i++ adds one to i. The loop in the example starts at 1 and runs while i is 3 or less, so it runs three times.
The variable i can be used inside the block, and it has a different value on each pass.
for (let i = 1; i <= 3; i++) {
console.log(i);
}Your turn: counting
Change where the loop starts and stops.
Practice task
Use a for loop to print the numbers from 1 to 5, one on each line.
Your answer is run and checked in the lesson. Create a free account to try it.
Building up a result
A loop is often used to build up one answer. Create a variable before the loop, change it inside the loop, and use it after the loop.
total += i is a short way to write total = total + i.
The example adds the numbers 1 to 4. The print is after the closing bracket, so it runs once, at the end.
let total = 0;
for (let i = 1; i <= 4; i++) {
total += i;
}
console.log(total);The while loop
A while loop repeats for as long as its condition is true. Use it when you do not know in advance how many passes are needed.
Something inside the loop must change so that the condition becomes false. If nothing does, the loop never ends. Here the lesson stops such a program after a few seconds.
The example halves a number until it drops below 10.
let n = 80;
while (n >= 10) {
console.log(n);
n = n / 2;
}Your turn: a total
Combine a loop with a running total.
Practice task
Use a loop to add the numbers from 1 to 10, then print the total once.
Your answer is run and checked in the lesson. Create a free account to try it.