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.
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
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
- JavaScript Guide (MDN)
- The Python Tutorial (Python documentation)