JavaScript Reference ยท Statements and Declarations
The if...else statement
Reference for the JavaScript if...else statement: conditions, truthy and falsy values, else if chains, braces, the dangling else and common mistakes.
The if statement runs a statement when a condition is truthy. An optional else branch runs when it is falsy. Chain several tests with else if. The condition is converted to a boolean using the usual truthy and falsy rules, so it does not have to be a real true or false.
if (score >= 50) { console.log("pass"); } else { console.log("fail"); }
Try it
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Syntax
if (condition) statement1 if (condition) statement1 else statement2 if (condition1) { // ... } else if (condition2) { // ... } else { // ... }
| Part | Description |
|---|---|
condition |
An expression; its value is converted to a boolean. |
statement1 |
Runs when the condition is truthy. Usually a block { ... }. |
statement2 |
Runs when the condition is falsy. Can be another if. |
Usage notes
- Falsy values are
false,0,-0,0n,"",null,undefinedandNaN. Everything else is truthy, including"0","false",[]and{}. - Always use braces. Without them only the next single statement belongs to the branch, and adding a second line later silently runs it unconditionally.
- Dangling else. An
elseattaches to the nearest unmatchedif. Braces make the intent explicit. =versus===.if (x = 3)assigns; it is almost always a typo. Linters flag it. Prefer strict equality (===) over==unless you want type coercion.- Early returns. Handling the error or edge case first and returning keeps the main path unindented and easier to read than deeply nested
elseblocks. - Alternatives. For choosing a value use the conditional operator (
a ? b : c); for many fixed values considerswitchor a lookup object; for defaults use??or||. - No block scope trick. Declaring a function inside an
ifwithout a block is only legal in sloppy mode; avoid it.
Browser support
Supported in every JavaScript engine.
Related
switch,break- Lessons: if...else, Ternary and switch, Comparison