8 / 12 · Intro
Loops: for and while
Adding up the whole numbers from 1 to 100 by hand takes a while. A three-line for loop does it at once and prints 5050.
Jump to the 10 practice questionsYou will learn
- Read the three parts of a for loop
- Build a total with an accumulator
- Repeat with while and control a loop with break and continue
Before this: Making decisions with if and else in JavaScript
1Explain
The for loop
The parentheses after for hold three parts separated by semicolons. The first, let i = 1, runs once before the loop starts and creates a counter variable. The second, i <= 5, is the condition, checked before every round; when it becomes false, the loop ends.
Watch i: it starts at 1, the block runs while i <= 5 is true, and i++ adds 1 after each round.
for (let i = 1; i <= 5; i++) {console.log(i);}// prints 1, 2, 3, 4, 5 on separate lines
1 2 3 4 5
2Explore
Start, stop, step
Change the start, the last allowed value and the step, and count the lines that come out.
for (let i = 1; i <= 5; i += 1) {
console.log(i);
}1
2
3
4
53Problem
How many lines?
How many lines does this print?
for (let i = 0; i < 4; i++) {
console.log(i);
}Hint
List the values of i that pass i < 4.
Solution
Answer: 4
i takes the values 0, 1, 2 and 3. At 4 the condition i < 4 is false.
4Explain
Building up a total
The most common loop pattern is the accumulator. Make a variable before the loop, update it inside, and use it after. Here is the sum from the lead:
sum is made before the loop, grows inside it and is printed after it. Here the loop runs to 5; the lesson's version runs to 100 and prints 5050.
let sum = 0;for (let i = 1; i <= 5; i++) {sum += i;}console.log(sum);
15
5Problem
Add 1 to 4
What does this print?
let total = 0;
for (let i = 1; i <= 4; i++) {
total += i;
}
console.log(total);Hint
Add the values i takes: 1, 2, 3, 4.
Solution
Answer: 10
1 + 2 + 3 + 4 = 10.
6Explain
The while loop
A while loop has only a condition. It keeps running its block as long as the condition is true. Use it when you do not know in advance how many rounds you need, such as doubling a number until it passes 1,000.
n doubles until it passes 1000; steps counts the rounds.
let n = 1;let steps = 0;while (n <= 1000) {n *= 2;steps++;}console.log(n, steps); // 1024 10
1024 10
7Problem
Take away 3 until …
What does this print?
let n = 10;
while (n > 3) {
n -= 3;
}
console.log(n);Hint
Write n after each round: 10, 7, …
Solution
Answer: 1
10, 7, 4, 1. At 1 the condition 1 > 3 is false.
8Explain
break and continue
Two keywords change the flow inside a loop. break leaves the loop at once. continue skips the rest of the current iteration and jumps to the next one. For example, a loop over 1 to 10 with if (i % 3 === 0) continue; at the top prints every number except 3, 6 and 9.
for (let i = 1; i <= 10; i++) {
if (i % 2 === 0) continue;
if (i > 7) break;
console.log(i);
}1
3
5
79Problem
Where does break stop?
What does this print?
for (let i = 1; i <= 10; i++) {
if (i === 4) break;
console.log(i);
}Hint
The check for 4 comes before console.log.
Solution
Answer: 1 2 3 on separate lines
At i = 4, break leaves the loop before printing.
10Practice
Add 1 to 100
Write a for loop that adds the whole numbers from 1 to 100 into sum, so the program prints 5050.
5050let sum = 0;
// Add a for loop here that adds
// 1, 2, 3 ... 100 to sum.
console.log(sum);
Hint
i <= 100 includes 100; i < 100 stops at 99.
A solution
let sum = 0;
for (let i = 1; i <= 100; i++) {
sum += i;
}
console.log(sum);11Practice
Countdown and liftoff
The countdown prints 3, 2, 1. Add a line after the loop so it then prints Liftoff!.
3
2
1
Liftoff!let n = 3;
while (n > 0) {
console.log(n);
n = n - 1;
}
Hint
A line after the closing brace runs once, after the loop.
A solution
let n = 3;
while (n > 0) {
console.log(n);
n = n - 1;
}
console.log("Liftoff!");12Explain
Common mistakes
for (let i = 0; i < 3; i++) {
console.log(i);
}
console.log(i);0
1
2
ReferenceError: i is not defined (line 4)
- The word before the colon names the kind of error: ReferenceError, TypeError, SyntaxError.
- After the colon: what went wrong, usually with the name involved.
- The line number shows where the program stopped. A SyntaxError stops it before any line runs.
A counter declared with let in the for line exists only inside the loop. To use the last value afterwards, declare it before the loop.
13
Summary
- for (start; condition; update) { ... } repeats while the condition is true.
- Make accumulators before the loop, update them inside, use them after.
- while (condition) { ... } suits loops with an unknown number of rounds.
- Something must make the condition false, or the loop never ends.
- break leaves the loop; continue skips to the next round.