Skip to content
Tutorials Center
My learning

Topics

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.

JavaScript
if (score >= 50) {
  console.log("pass");
} else {
  console.log("fail");
}

Try it

JS Choosing a branch

Press Run (or Ctrl + Enter) to see the console output here.

No output.

JS Truthy, falsy and a classic mistake

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Syntax

JavaScript
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, undefined and NaN. 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 else attaches to the nearest unmatched if. 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 else blocks.
  • Alternatives. For choosing a value use the conditional operator (a ? b : c); for many fixed values consider switch or a lookup object; for defaults use ?? or ||.
  • No block scope trick. Declaring a function inside an if without a block is only legal in sloppy mode; avoid it.

Browser support

Supported in every JavaScript engine.