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
switchuses strict (===) comparison between the switched value and eachcase.- Without a
break,return, orthrow, execution falls through into the nextcaseregardless of whether it matches — sometimes used deliberately to group cases (case 'a': case 'b': …), but a frequent source of bugs when accidental. defaultdoesn’t have to be last, but placing it last reads most naturally, and it doesn’t need abreaksince nothing follows it.if/elsebodies wrapped in{ }create a block scope for anylet/constdeclared inside.
Common mistakes
- Forgetting
breakin aswitchcase, causing unintended fall-through. - Chaining many
else ifbranches that all test the same variable for equality — aswitch(or, in some cases, an object/Maplookup) usually reads more clearly.
Runtime notes
Both statements are core ECMAScript with identical behavior in every browser and Node version.