Chapter V · Control Flow
The else Statement
else attaches a fallback block to an if statement, so exactly one of the two paths always runs — never both, never neither.
01 What Is the else Statement?
else can only appear directly after an if block (or another else if). It defines what should happen when the preceding condition was falsy — a value JavaScript treats as false. Together, if/else guarantee that one of the two branches executes, covering every possible outcome of the condition.
02 Simple Example
Two mutually exclusive outcomes based on the time of day.
const hour = 14;\n\nif (hour < 12) {\n console.log("Good morning");\n} else {\n console.log("Good afternoon");\n}
14 < 12 is false, so the engine never even looks inside the if block — it jumps straight to else and logs "Good afternoon".
03 How It Works
The engine checks the if condition exactly once. A falsy result means the if block is skipped and the attached else block runs automatically — there's no separate condition to check for else itself, which is what makes the two branches mutually exclusive.
04 Step-by-Step
Evaluate the if condition.
If truthy, run the if block and skip else entirely.
If falsy, skip the if block and run the else block instead.
Continue with whatever code follows the whole if/else structure.
05 Common Mistakes & Edge Cases
else is optional — an if with no else simply does nothing on a falsy condition, rather than being an error. Add else only when there's a genuine alternative action to take.
Warning: An else can only attach to the if (or else if) immediately before it, syntactically. A stray else with no matching if is a SyntaxError.
06 Mental Model
"A fork with exactly two roads — you always end up on one."
Unlike a plain if, which leaves a gap when the condition is false, if/else guarantees you land somewhere: one path is always taken, the other is always skipped.
07 Interview Questions
Q: Can if/else be replaced by a ternary here?
For a single value, yes: const greeting = hour < 12 ? "Good morning" : "Good afternoon" — but if/else stays clearer once either branch needs more than one statement.
Key Takeaway
else runs precisely when the preceding if condition was false, making the pair exhaustive: one branch always executes, the other never does.