DEV Community

Iineman2
Iineman2

Posted on Originally published at codeglyphs.hashnode.dev

Why Your `if / else` Took the Wrong Branch: 4 JavaScript Condition Traps

"My if is wrong" is almost never true. The if did exactly what you wrote. It just took a different branch from the one you had in your head.

That gap between the branch you expected and the branch that ran is where most beginner conditional bugs live, and it narrows fast once you do one thing: for a concrete input, say out loud which condition is checked first, what it evaluates to, and which line runs next.

This post walks through four traps. Each has a snippet, a Predict which path runs prompt (answer it before you read on), the reason it happens, and a lab: the broken function loaded into a step-through visualizer, where you can watch the branch being chosen, fix it, and get checked against hidden cases.

The labs use Code Glyphs, a browser step-through tool I built. You can follow every snippet in Node or the browser console without it.

How the labs work. Each one opens with the broken function loaded. Press Step to advance one stroke at a time (the if conditions show up as "gates" you can watch answer yes or no) or Run to jump to the result. Edit the shape or the JavaScript pane, then press Check my shape: it runs your fix on the cases shown and on hidden ones. Opening a lab link doesn't run anything until you press a button.

If an embedded lab doesn't load where you're reading, each one has a plain link right under it.


Trap 1: Checking the broad condition before the specific one

function grade(score) {
  if (score >= 60) {
    return "C";
  } else if (score >= 75) {
    return "B";
  } else if (score >= 90) {
    return "A";
  } else {
    return "F";
  }
}

grade(93);
Enter fullscreen mode Exit fullscreen mode

Predict which path runs. For score = 93, which return line executes? And for 82?

What happens. grade(93) returns "C", and so does grade(82). An if / else if chain is a "first match wins" sieve. 93 >= 60 is true, so that branch runs and the chain stops. The >= 75 and >= 90 lines are never reached, for any score, because anything that passes them has already passed >= 60. The correct answer for 93 is "A".

The mental model. Each condition in the chain says yes to everything it covers, including inputs that a later, more specific condition was written to catch. score >= 60 is true for 93 too. So the order of the chain matters: put the narrowest condition first (the one fewest inputs satisfy), and let each later condition be a little wider.

The same bug shows up in the classic FizzBuzz when the single divisors come first:

if (n % 3 === 0)  return "Fizz";      // 15 lands here and stops
else if (n % 5 === 0)  return "Buzz";
else if (n % 15 === 0) return "FizzBuzz";   // never reached
Enter fullscreen mode Exit fullscreen mode

label(15) returns "Fizz" this way (and label(30) too). Put the % 15 check first and it returns "FizzBuzz".

If you'd rather not depend on order, bound each branch on both sides, like score >= 60 && score < 75. It is longer, but every branch then stands on its own.

Lab: fix grade. Step through grade(93) and watch which gate answers yes first.

Open this lab in a new tab


Trap 2: > vs >= at the boundary

function shipping(order) {
  if (order > 50) {
    return 0;
  }
  return 5;
}

shipping(50);
Enter fullscreen mode Exit fullscreen mode

The rule is "orders of 50 or more ship free."

Predict which path runs. What does shipping(50) return? What about 49 and 51?

What happens. shipping(50) returns 5, but it should return 0. 50 > 50 is false, so the order falls through to the 5.

order with > with >=
49 5 5
50 5 0
51 0 0

Only the middle row differs, which is why this bug survives casual testing: 49 and 51 both look right.

The mental model. Boundary bugs only show up on the boundary. Whenever a rule has a number in it, test three values: just below it, exactly on it, just above it. And translate the English into operators deliberately:

The rule says Write
"at least 50", "50 or more" >= 50
"more than 50", "over 50" > 50
"at most 50", "up to and including 50" <= 50
"under 50", "less than 50" < 50

Lab: fix shipping. Case 1 is the boundary itself.

Open this lab in a new tab


Trap 3: && vs ||, and negating a compound condition

function unsafe(temp) {
  if (temp < 5 && temp > 30) {
    return true;
  }
  return false;
}

unsafe(2);
Enter fullscreen mode Exit fullscreen mode

The safe range is 5 to 30 inclusive, and unsafe should say whether temp is outside it.

Predict which path runs. What does unsafe(2) return? Is there any number for which it returns true?

What happens. unsafe(2) returns false, but the answer should be true. 2 < 5 is true, but 2 > 30 is false, so && fails. And there is no such number: nothing is both below 5 and above 30, so the function returns false for every input.

The mental model.

  • A && B means both must hold. It only ever narrows the set of inputs that get in.
  • A || B means either may hold. It widens the set.

"Outside the range" means "too low or too high": two ways in, so ||. The mirror bug is just as common. If you write the inside check as temp >= 5 || temp <= 30, it is true for every number, because every number is at least 5 or at most 30.

When you negate a compound condition, the operator flips and each part is negated (De Morgan's laws):

!(a && b)  ===  !a || !b
!(a || b)  ===  !a && !b
Enter fullscreen mode Exit fullscreen mode

Here it is checked on every combination of a and b:

| a | b | !(a && b) | !a \|\| !b | !a && !b |
| --- | --- | --- | --- | --- |
| true | true | false | false | false |
| true | false | true | true | false |
| false | true | true | true | false |
| false | false | true | true | true |

The third column always matches the fourth, never the fifth. So !(temp >= 5 && temp <= 30) is the same as temp < 5 || temp > 30. I checked it for every whole number from -10 to 50. A common slip is to negate the parts but forget to flip && into ||.

Lab: fix unsafe. Hidden cases sit right on the edges (5 and 30), so trap 2 is waiting there too.

Open this lab in a new tab


Trap 4: No fallback branch (and nested ternaries)

function sizeLabel(cm) {
  if (cm < 10) {
    return "small";
  } else if (cm < 20) {
    return "medium";
  } else if (cm < 30) {
    return "large";
  }
}

sizeLabel(45);
Enter fullscreen mode Exit fullscreen mode

Predict which path runs. Which return line runs for cm = 45? What does the function hand back?

What happens. None of them. All three conditions are false, the chain ends, and a function that finishes without hitting a return gives back undefined. Expected: "xl".

The mental model. An if / else if chain with no final else has a hidden branch: "nothing matched, do nothing". Ask of every chain, what happens when none of the conditions is true? If the honest answer is "that can't happen", write the else anyway and make it return something loud or obviously wrong. A silent undefined travels a long way before it breaks something.

Nested ternaries make the same chain shorter, and syntax forces you to write the last else:

const label = cm < 10 ? "small"
            : cm < 20 ? "medium"
            : cm < 30 ? "large"
            : "xl";
Enter fullscreen mode Exit fullscreen mode

That version is fine when each line is a plain value. Two ways it goes wrong:

  • Precedence. Ternary binds more loosely than + and ===. This line is meant to print "Found 1 item", but
  "Found " + count + count === 1 ? " item" : " items"
Enter fullscreen mode Exit fullscreen mode

is parsed as ("Found " + count + count === 1) ? " item" : " items". The text before ? is a string compared to 1, which is never true, so the result for count = 1 is just " items": the "Found" part is gone as well. Wrap the ternary in parentheses: "Found " + count + (count === 1 ? " item" : " items") gives "Found 1 item".

  • Readability. Once a branch needs more than a value, switch back to if / else.

Lab: fix sizeLabel. Step through sizeLabel(45) and watch the function reach the closing brace without returning.

Open this lab in a new tab


Practice: call the gate

Two read-only puzzles from the free tier. You don't write any code. The run pauses at a gate (an if or loop condition), and you call whether it answers yes or no. Work out the values on paper first.

Call the gate: first height over 5

Open this puzzle in a new tab

Call the gate: gold, silver or bronze

Open this puzzle in a new tab


A 60-second branch review

For any if chain, pick one concrete input and answer these:

  1. Which condition is checked first, and is it the narrowest one?
  2. Do the boundary values (just below, on, just above) each land where the rule says?
  3. In every && / ||, would I get the same answer if I read it aloud in plain English?
  4. If I negated a compound condition, did the operator flip?
  5. What happens when none of the branches match?

Then step through it once with the input that worries you most. The wrong branch is usually visible in the first gate.

Top comments (0)