Skip to content

if / else if / else

The Course
•
17 min study

Conditions: questions with a true or false answer

A program often has to choose: show "Goal reached" only if the learner studied enough. The question it asks is a condition, an expression whose value is true or false. Comparison operators build most conditions:

OperatorMeansminutes = 30 gives
>greater thanminutes > 30 is false
>=greater than or equal tominutes >= 30 is true
<less thanminutes < 30 is false
<=less than or equal tominutes <= 30 is true
===equal: same type and same valueminutes === 30 is true
!==not equalminutes !== 30 is false

A single = stores a value; it never compares. Use three equals signs to compare. === is strict: "30" === 30 is false because one is a string and the other is a number. JavaScript also has a loose == that converts types first, so "30" == 30 is true. Those silent conversions hide bugs, so this course always uses === and !==.

Comparisons produce booleans JavaScript
const minutes = 30;
console.log(minutes >= 30);
console.log(minutes < 30);
console.log(minutes === 30);
console.log("30" === 30);
Check your prediction
Text
true
false
true
false

An if statement uses a condition to decide whether a block runs:

JavaScript
if (minutes >= 30) {          // the condition goes in parentheses
  console.log("Goal reached"); // the block in braces runs only when it is true
} else {
  console.log("Keep going");   // the else block runs only when it is false
}

Exactly one of the two blocks runs. The else part is optional; leave it out when nothing should happen on false.

Predict before running

Which message appears at exactly 30? Change the minutes to 29 after checking.

Predict, then run JavaScript
const minutes = 30;

if (minutes >= 30) {
  console.log("Goal reached");
} else {
  console.log("Keep going");
}

console.log("30" === 30);
Check your prediction
Text
Goal reached
false

Trace each statement in order. If your prediction differed, describe the first place your mental model and the result diverged before trying again.

Order matters in a decision chain

The first true branch wins in an if/else-if chain. If you check a broad category first, a more specific category later may never be reached. Think of the branches as a sequence of questions rather than independent labels.

Here the requirements are exclusive: at least 60 minutes is excellent; otherwise at least 30 is a good start. What would happen if you swapped the conditions without changing the labels?

Order matters in a decision chain JavaScript
const minutes = 75;

if (minutes >= 60) {
  console.log("Excellent");
} else if (minutes >= 30) {
  console.log("Good start");
} else {
  console.log("A small beginning");
}
Check your prediction
Text
Excellent

Putting minutes >= 30 first would classify 75 as Good start. The program would run, but the policy would be wrong.

Independent questions versus one choice

Two separate if statements can both run. An if/else chain selects one branch. Use separate statements for independent actions—for example, congratulate a learner for reaching a goal and separately remind them to take a break. Use a chain for exactly one category.

Write a boundary table before coding:

MinutesRequired category
29A small beginning
30Good start
59Good start
60Excellent

Bug hunt: change minutes >= 60 to minutes > 60. Which row catches the mistake? Testing only 75 would miss it. Fix the operator, then explain why a semicolon directly after if (condition) would end the statement before the intended block.

Separate overlapping questions from exclusive outcomes

An else-if chain chooses one outcome. Separate if statements ask independent questions, even when the first one is true. Neither shape is automatically better; choose the one matching the problem. A shipping price usually needs one band, while a number can satisfy several properties.

Put overlapping bands in an order that does not hide a more specific case. Testing a small threshold first can make a later large threshold unreachable for exactly the values it was intended to handle. Boundary inputs expose this faster than trying many unrelated values.

One band for one purchase JavaScript
const amount = 65;

if (amount >= 50) {
  console.log("free");
} else if (amount >= 20) {
  console.log("reduced");
} else {
  console.log("standard");
}
Check your prediction
Text
free

65 satisfies both thresholds, but the first true branch wins. Reversing the two comparisons would print reduced. Trace 19, 20, 49 and 50 to determine exactly where each outcome begins.

Two independent facts JavaScript
const n = 15;

if (n % 3 === 0) {
  console.log("divides by 3");
}

if (n % 5 === 0) {
  console.log("divides by 5");
}

console.log("checked");
Check your prediction
Text
divides by 3
divides by 5
checked

The second if is not attached to the first. Both questions can succeed. The final statement is outside both blocks and runs regardless. Braces, rather than indentation, determine that grouping in JavaScript.

Try the rule on new inputs

Change the second if to else if and predict the missing line. Then repair a shipping chain whose >=20 branch comes before >=50. Explain the bug using amount=50, not just the original 65.

Before you move on

Before writing a chain, list a value just below and exactly on each threshold, and say which message each should print. An else if chain runs only the first true branch; separate if statements can all run.

Your turn

Exercise

if / else if / else: practice

Print Short session below 15 minutes, Steady session from 15 through 44, and Long session from 45 upward. Start with 15; then test 14, 44, and 45.

Your working space JavaScript
const minutes = 15;
// Choose one of the three messages.
Hint 1: the idea

Test the smallest band first. Once it fails, you already know minutes is at least 15.

Hint 2: a first step

Start with if (minutes < 15) and the Short session message. Run it with 14 and see it print. The remaining branches follow the same pattern for the next band up.

Show one solution
JavaScript
const minutes = 15;

if (minutes < 15) {
  console.log("Short session");
} else if (minutes < 45) {
  console.log("Steady session");
} else {
  console.log("Long session");
}
Text
Steady session

Only one branch runs. The second condition does not need to repeat minutes >= 15 because reaching it already establishes that fact.

What you should be able to explain

  • When should two if statements replace an if/else chain?
  • Why must the excellent category be checked first in this example?
  • Which inputs distinguish greater-than from greater-than-or-equal?

Was this article helpful?

Your response is saved on this device.