if / else and switch

Branching statements — if/else for arbitrary conditions, switch for one value compared against several exact matches.

                if (cond) { } else { } / switch (value) { case x: … }
              

Purpose

if/else runs a block based on an arbitrary boolean condition, with as many else if branches as needed. switch compares one value against several exact case matches — clearer than a long else if chain when every branch tests the same value.

Syntax

if (score >= 90) {
  grade = 'A';
} else if (score >= 80) {
  grade = 'B';
} else {
  grade = 'C or below';
}

switch (status) {
  case 'loading':
    message = 'Please wait…';
    break;
  case 'error':
    message = 'Something went wrong.';
    break;
  default:
    message = 'Ready.';
}

Behavior notes

  • switch uses strict (===) comparison between the switched value and each case.
  • Without a break, return, or throw, execution falls through into the next case regardless of whether it matches — sometimes used deliberately to group cases (case 'a': case 'b': …), but a frequent source of bugs when accidental.
  • default doesn’t have to be last, but placing it last reads most naturally, and it doesn’t need a break since nothing follows it.
  • if/else bodies wrapped in { } create a block scope for any let/const declared inside.

Common mistakes

  • Forgetting break in a switch case, causing unintended fall-through.
  • Chaining many else if branches that all test the same variable for equality — a switch (or, in some cases, an object/Map lookup) usually reads more clearly.

Runtime notes

Both statements are core ECMAScript with identical behavior in every browser and Node version.

Taught in these lessons

Related reference