JavaScript if...else Statement
The if...else statement runs a block of code when a condition is truthy, and optionally another block when it is falsy.
Description
The if statement runs a statement or block if its condition is truthy. An optional else clause runs when it's falsy, and else if chains let you test several conditions in turn; only the first matching branch runs.
The condition is converted to a boolean, so values like 0, '', null and undefined count as false. Always use braces, even for single statements, to avoid mistakes when adding lines later. When you just need to choose a value, the conditional operator ?: is more compact, and for comparing one value against many fixed options, switch or a lookup object can be clearer.
Conditions often combine several checks with the logical operators &&, || and !. Comparisons should normally use === and !==, so that values aren't converted unexpectedly. Deeply nested if statements become hard to follow; returning early from a function ("guard clauses") or splitting the logic into smaller functions usually keeps code flatter and easier to read.
Syntax
if (condition) {
statements
} else if (otherCondition) {
statements
} else {
statements
}Example
Browser Support
The following information will show you the current browser support for the if...else statement. Hover over a browser icon to see the version that first introduced support for this statement.
Desktop





Tablets & Mobile





