else
In JavaScript, the else keyword introduces the optional clause that an if statement runs when its condition is falsy. It never appears on its own: every else belongs to an if, and the code after it can be a single statement or a block.
JavaScript has no elseif keyword. An else if chain is an else clause whose statement is another if, so the conditions are tested in order and only the first truthy branch runs. When braces are left out, an else pairs with the nearest if that doesn’t already have one, which is the classic dangling-else rule.
For choosing between many fixed values, a switch statement is an alternative. else is a reserved word and has been part of the language since the first edition of ECMAScript.
JavaScript else Keyword Syntax
An else clause always follows an if statement, and it can chain into another if:
if (<condition>) <statement>
else <statement>
if (<condition1>) {
<statements>
} else if (<condition2>) {
<statements>
} [else {
<statements>
}]
JavaScript else Keyword Examples
An else if chain tests conditions in order and falls back to a final else:
> function describeTemperature(celsius) {
… if (celsius < 0) {
… return "freezing";
… } else if (celsius < 20) {
… return "cool";
… } else {
… return "warm";
… }
… }
undefined
> describeTemperature(-5)
'freezing'
> describeTemperature(12)
'cool'
> describeTemperature(31)
'warm'
The conditions are checked from top to bottom. A value of 12 fails the first test and passes the second, so the final else branch never runs for it.
Without braces, an else attaches to the innermost if, whatever the indentation suggests:
> function checkAccess(isLoggedIn, isAdmin) {
… if (isLoggedIn)
… if (isAdmin) return "admin";
… else return "guest";
… return "anonymous";
… }
undefined
> checkAccess(true, false)
'guest'
> checkAccess(false, false)
'anonymous'
The else belongs to if (isAdmin), not to if (isLoggedIn), so a logged-out user skips it entirely.
JavaScript else Keyword Use Cases
- Running a fallback branch when a condition is falsy
- Choosing one of several branches with an
else ifchain - Handling the default case after a series of range checks
- Returning or assigning one of two values when a ternary would be hard to read
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