if
In JavaScript, the if keyword starts a conditional statement that runs its body only when a condition is truthy. An optional else clause holds a second statement that runs when the condition is falsy. The condition can be any expression, and JavaScript converts its result to a boolean to decide which branch runs.
The falsy values are false, 0, -0, 0n, NaN, the empty string, null, and undefined. Every other value is truthy, including empty arrays and objects. JavaScript has no elseif keyword. An else if chain is an if statement nested in an else clause, and an else always pairs with the nearest if that doesn’t have one yet. For one value compared against many cases, switch is an alternative.
The body is a single statement, usually a block in braces. A let, const, or class declaration can’t be the body on its own, so it needs braces around it. ECMAScript has had if since its first edition.
JavaScript if Keyword Syntax
An if statement runs a single statement or a block, with an optional else clause:
if (<condition>) <statement> [else <statement2>]
if (<condition>) {
<statements>
} [else if (<condition2>) {
<statements2>
}] [else {
<statements3>
}]
JavaScript if Keyword Examples
An if...else if...else statement picks the first branch whose condition is truthy:
> const temperature = 18;
undefined
> if (temperature > 25) {
… "hot";
… } else if (temperature > 15) {
… "mild";
… } else {
… "cold";
… }
'mild'
The REPL echoes 'mild' because that branch’s last expression is the completion value of the whole statement.
Empty arrays are truthy, so checking a collection’s size takes an explicit comparison:
> const items = [];
undefined
> if (items) "has a value";
'has a value'
> if (items.length > 0) "has items";
undefined
JavaScript if Keyword Use Cases
- Running code only when a condition holds
- Choosing between two or more branches with
elseandelse if - Returning early from a function when an input is invalid
- Guarding against
nullorundefinedbefore reading a property
Have a question about this? Mentor AI can show you examples, compare related terms, and point you to tutorials.
By Leodanis Pozo Ramos • Updated Nov. 4, 2026