Lesson 2 · Unit 02
Loops
Repeat a block with while and for, and trace it by hand
What you practise
whilewith a counter, the three parts offor,for...of,breakandcontinue, a running total, tracing a loop by hand, the loop that never ends
Try a question from this lesson
Pick one
while repeats its block for as long as the condition is true. How many times does this print hi?
let count = 0;
while (count < 3) {
console.log("hi");
count = count + 1;
}Hint
Follow count: what is it at the start of each trip, and when is the condition first false?
Correct answer
3
Why
The trips happen with count at 0, 1 and 2. After the third trip count is 3, the condition 3 < 3 is false, and the loop ends. A while is an if that goes back and asks again.
The ideas
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
Trace it by hand
To know what a loop does, be the computer. Make a small table: one row per trip, one column per variable.
Before each trip, check the condition with the current values. Stop at the first row where it is false.
It feels slow. It is also how every programmer finds out why a loop misbehaves.
count count < 3 prints
0 true hi
1 true hi
2 true hi
3 false (loop ends)Concept
for: a counter in one line
Counting loops are so common that they have their own form. The brackets of for hold three parts, split by semicolons.
The start, run once: let i = 0. The condition, checked before every trip: i < 3. The step, run after every trip: i++, which is short for i = i + 1.
In the same spirit, total += i is short for total = total + i.
for (let i = 0; i < 3; i++) {
console.log(i);
}
// prints 0, 1, 2Concept
break and continue
Two statements change the path of a loop.
break leaves the loop at once. The program carries on after the loop's closing bracket.
continue abandons the current trip and jumps to the next one.
Both normally sit inside an if. When an if controls a single statement, the curly brackets may be left out.
for (let i = 1; i <= 5; i++) {
if (i === 2) continue;
if (i === 4) break;
console.log(i);
}
// prints 1, 39 more exercises in the app
- 4× type the answer
- 2× multiple choice
- 1× fill the blanks
- 1× order the lines
- 1× true or false
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.