ECMAScript® 2024 Language Specification

Draft ECMA-262 / February 15, 2024

14.6 The if Statement

Syntax

IfStatement[Yield, Await, Return] : if ( Expression[+In, ?Yield, ?Await] ) Statement[?Yield, ?Await, ?Return] else Statement[?Yield, ?Await, ?Return] if ( Expression[+In, ?Yield, ?Await] ) Statement[?Yield, ?Await, ?Return] [lookahead ≠ else] Note
The lookahead-restriction [lookahead ≠ else] resolves the classic "dangling else" problem in the usual way. That is, when the choice of associated if is otherwise ambiguous, the else is associated with the nearest (innermost) of the candidate ifs

14.6.1 Static Semantics: Early Errors

IfStatement : if ( Expression ) Statement else Statement IfStatement : if ( Expression ) Statement Note

It is only necessary to apply this rule if the extension specified in B.3.1 is implemented.

14.6.2 Runtime Semantics: Evaluation

IfStatement : if ( Expression ) Statement else Statement
  1. Let exprRef be ? Evaluation of Expression.
  2. Let exprValue be ToBoolean(? GetValue(exprRef)).
  3. If exprValue is true, then
    1. Let stmtCompletion be Completion(Evaluation of the first Statement).
  4. Else,
    1. Let stmtCompletion be Completion(Evaluation of the second Statement).
  5. Return ? UpdateEmpty(stmtCompletion, undefined).
IfStatement : if ( Expression ) Statement
  1. Let exprRef be ? Evaluation of Expression.
  2. Let exprValue be ToBoolean(? GetValue(exprRef)).
  3. If exprValue is false, then
    1. Return undefined.
  4. Else,
    1. Let stmtCompletion be Completion(Evaluation of Statement).
    2. Return ? UpdateEmpty(stmtCompletion, undefined).