Lesson 2 · Unit 02
Loops
while, for and for...of, break and continue, and tracing a loop 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
A while loop repeats its block for as long as its condition is true. How many lines does this print?
let count = 1;
while (count <= 3) {
console.log(count);
count = count + 1;
}Hint
Follow count: write down its value each time the condition is checked.
Correct answer
3
Why
It prints 1, 2 and 3. Each round adds 1 to count. When count reaches 4, the condition 4 <= 3 is false and the loop ends. An if would have run the block once. A while goes back and checks again.
The ideas
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
while
while checks its condition. If it is true, the block runs, and then the condition is checked again.
Something inside the block must change, or the condition stays true forever.
n -= 1 is short for n = n - 1. There is also +=, and n++ adds exactly 1.
let n = 3;
while (n > 0) {
console.log(n);
n -= 1;
}
console.log("Liftoff");
// 3, 2, 1, LiftoffConcept
for
Counting loops always have three parts: where to start, when to keep going, and how to step.
for puts all three on one line, separated by semicolons. The counter is usually called i.
The step runs at the end of every round, before the condition is checked again.
for (let i = 1; i <= 3; i++) {
console.log(i);
}
// start: let i = 1
// keep going if: i <= 3
// after a round: i++Concept
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 skips the rest of this round only. The loop goes on with the next round.
for (let i = 1; i <= 5; i++) {
if (i === 2) { continue; }
if (i === 4) { break; }
console.log(i);
}
// prints 1, then 39 more exercises in the app
- 4× type the answer
- 2× multiple choice
- 1× fill the blanks
- 1× true or false
- 1× order the lines
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.