JavaScript: Conditionals
Control which code runs based on conditions: if, else if, switch, ternary, and short-circuit patterns.
if Statement
The if statement runs a block of code only when its condition is truthy. If the condition is falsy the block is skipped entirely.
if Statement
The most fundamental decision-making construct in JavaScript.
- Syntax:
if (condition) { /* block */ } - The condition is coerced to boolean, any truthy value enters the block
- Curly braces are optional for single statements but always recommended
- The condition can be any expression: comparison, function call, variable
if Statement
Always use curly braces, single-line if without braces is a common bug source.
Press Run to execute the code and see output here.
if...else Statement
Adding else provides a block that runs when the condition is falsy, exactly one of the two branches always executes.
if...else
Guarantees one of two code paths always runs either if or else, never both.
- The else block runs when the if condition is falsy
- Exactly one branch runs, they are mutually exclusive
- else does not take its own condition that is what else if is for
if...else
One branch always runs, use ternary for the simple 'assign one of two values' pattern.
Press Run to execute the code and see output here.
else if Chains
Chain multiple conditions with else if. JavaScript evaluates them top to bottom and executes the first block whose condition is truthy, the rest are skipped.
else if Chain
Tests conditions in order, only the first matching branch runs.
- Order matters put the most specific conditions first
- At most one branch executes, even if multiple conditions would be true
- The final
elseis optional but acts as a catch-all default - Long chains may be cleaner as a
switchstatement
else if Chain
Each condition is only checked if all previous ones were false.
Press Run to execute the code and see output here.
Nested Conditionals
An if statement can contain another if inside it. Nesting is fine for two levels deeper than that, consider refactoring with early returns or combining conditions with &&.
Nested Conditionals
Keep nesting shallow, deep nesting is a readability red flag.
- Each inner if is only reached if the outer condition is true
- More than 2–3 levels deep is a sign to refactor
- Early return pattern: return/throw early to reduce nesting
- Combine conditions with
&&when both must be true anyway
Nested vs Flat Conditionals
The early-return / guard-clause pattern keeps nesting at one level.
Press Run to execute the code and see output here.
switch Statement
switch compares a single value against multiple cases using strict equality (===). It is cleaner than a long else if chain when testing one variable against several fixed values.
switch Statement
Maps a single value to one of many fixed cases, uses strict equality.
- Each
casemust end withbreakto prevent fall-through defaultruns when no case matches, equivalent to a finalelse- switch uses
===:case "1":will not match the number1 - Good for menus, status codes, command dispatch
switch Statement
Saturday and Sunday share a case by stacking, a common and clean pattern.
Press Run to execute the code and see output here.
switch with Fall-Through
When a break is omitted, execution falls through into the next case regardless of whether it matches. This is usually a bug but can be used intentionally to share logic across cases.
Fall-Through
Missing break causes execution to continue into the next case usually a bug, occasionally intentional.
- Without
break, JS runs the next case body even if the condition does not match - Intentional fall-through: stack cases with no body to group them
- Always add a comment when fall-through is intentional:
// fall-through returninside a function switch also stops fall-through
Fall-Through Behaviour
Accidental fall-through is a classic bug, always end every case with break unless grouping intentionally.
Press Run to execute the code and see output here.
Truthy and Falsy Values
Every value in JavaScript is either truthy or falsy when evaluated in a boolean context like an if condition. There are exactly six falsy values everything else is truthy.
The Six Falsy Values
Memorise these six, every other value is truthy, including [] and {}.
false0and-0and0n(BigInt zero)""(empty string)nullundefinedNaN- Truthy surprises:
"0",[],{}: all truthy!
Truthy and Falsy
"0", [], and {} are all truthy: the empty string "" is the only falsy string.
Press Run to execute the code and see output here.
| Value | Boolean result | Note |
|---|---|---|
| false | false | falsy |
| 0 | false | falsy |
| "" | false | falsy: empty string only |
| null | false | falsy |
| undefined | false | falsy |
| NaN | false | falsy |
| "0" | true | truthy: non-empty string |
| [] | true | truthy: even empty array |
| {} | true | truthy: even empty object |
| "false" | true | truthy: non-empty string |
Short-Circuit Evaluation
Logical operators && and || stop evaluating as soon as the result is determined. This property called short-circuiting is widely used as a compact alternative to simple if statements.
Short-Circuit Evaluation
&& stops at the first falsy value; || stops at the first truthy value.
a && b: evaluates b only if a is truthy; returns the deciding valuea || b: evaluates b only if a is falsy; returns the deciding value- Common pattern:
isLoggedIn && showDashboard(): guard before calling - Common pattern:
value || "default": fallback (use??for null/undefined only)
Short-Circuit Patterns
&& is a compact guard; || is a compact fallback: both return values, not just true/false.
Press Run to execute the code and see output here.
Conditional (Ternary) Operator
The ternary operator is a compact inline if...else that evaluates to a value. It is ideal for assigning one of two values or embedding a condition inside a template literal.
condition ? valueIfTrue : valueIfFalse
One expression, two outcomes: use for simple two-branch choices only.
- Syntax:
condition ? exprIfTrue : exprIfFalse - Both branches must be expressions not statements
- Can be used inside template literals and JSX
- Avoid nesting ternaries switch to
if/elsefor more than two outcomes
Ternary Operator
Perfect for simple two-outcome assignments: use if/else chains for three or more outcomes.
Press Run to execute the code and see output here.
Knowledge Check
1. What does an if statement do when its condition is falsy?
2. Which of the following values is falsy in JavaScript?
3. What happens in a switch statement when there is no break at the end of a case?
4. Which operator is used for the ternary (conditional) expression?
5. What does short-circuit evaluation mean for &&?
6. What is the correct syntax for an else if chain?
7. Which of the following is truthy?
8. What does switch use to compare a value against its cases?