Beginner 11 min

Branches and loops

Follow JavaScript conditions and count through a loop without a boundary error.

While loop
counter.js
let count = 0;
while (count < limit) {
count += 1;
}
console.log(count);
CURRENT STATE
00
11
22
33
44
55
Count 0Limit 5
Initialize the counter

Set count to zero before checking the loop condition.

Step 1 / 13

Compare explicitly

Use === for strict equality in introductory examples. The number 3 and text "3" are distinct values when compared this way. For an input that arrives as text, decide whether you should parse it into a number before comparing.

How it works

For a branch, ask which condition is true at the moment it is evaluated. For a loop, write the current counter, the condition result, and what changes before the next check. This makes a boundary mistake visible before you count the final output.

Separate the counter from the result

The diagram and sample increment a counter until it reaches the limit. For an exercise that counts only some of the visited numbers, keep a second variable for the result and change it only when the current number qualifies.

Code example

let count = 0;
const limit = 5;
while (count < limit) {
  count += 1;
  console.log(count);
}

Check your understanding

Count the multiples of 3 between 1 and the given limit, inclusive.

See the example and explanation
Example 1
Given 10
Answer 3
Example 2
Given 2
Answer 0

Maintain a counter of qualifying numbers and increment it whenever number % 3 === 0. The three matches up to 10 are 3, 6 and 9.

Open practice problem
Next lessonFunctions and scope