Skip to content

L02 Branches and comparisons

14 minSuggested first: L01 Values and assignments

Outcome

Evaluate a comparison and identify which branch runs, including at the boundary.

Learn

A condition is evaluated before the body of an if. An else runs when that condition is false. Equality doesn't satisfy "greater than" (>), but it does satisfy "greater than or equal to" (>=).

The conditional operator is a compact if/else that gives a value: cond ? a : b is a when cond is true and b otherwise. So n >= 5 ? n - 1 : n subtracts 1 only from 5 upward.

A useful reading technique: test a value just below, exactly at, and just above the cutoff.

Worked example

Here age is 18 and hasPass is false. What is label after the if? Then try it with hasPass set to true.

JavaScript
let label = "wait";
if (age >= 18 && hasPass) {
  label = "enter";
}
Predict first, then show the worked explanation

With age = 18, the first comparison, age >= 18, is true. The second term is false, so the whole && condition is false and label stays "wait". With hasPass = true, both parts are true and label changes to "enter".

Practice and check

Guided practice

Practice, not scored

Now age is 17 and hasPass is true. Which label remains after the if?

Choose one answer

Exit check

Counts toward completion

If n is 5, which value does if (n > 5) { result = "large"; } else { result = "small"; } assign to result?

Choose one answer

Common mistake

Assuming the second test always runs. In JavaScript, && skips its right operand when the left one is falsy. These examples use Boolean operands, so the result is always true or false and type conversion isn't a second puzzle.

Next

In the next lesson, follow a branch that runs again and again inside a loop.

References