Bitpath

Lesson 2 · Unit 02

Loops

while, for and for...of, break and continue, and tracing a loop by hand

13 exercisesabout 3 min

What you practise

  • while with a counter, the three parts of for, for...of, break and continue, 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?

JavaScript
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.

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.

JavaScript
let n = 3;
while (n > 0) {
  console.log(n);
  n -= 1;
}
console.log("Liftoff");
// 3, 2, 1, Liftoff

Concept

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.

JavaScript
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.

JavaScript
for (let i = 1; i <= 5; i++) {
  if (i === 2) { continue; }
  if (i === 4) { break; }
  console.log(i);
}
// prints 1, then 3

9 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.

One email when Bitpath is ready to try. Nothing else. Privacy