I couldn’t recall the rules for the if statement, so I looked at clause 12.5, but it wasn’t obvious to me still if the curly brace is necessary. So, I ask, where in Ecmascript 5.1 is it mentioned that no left curly brace in an if statement is acceptable?
Share
Here is the syntax of an if statement found in section 12.5:
IfStatement : if ( Expression ) Statement else Statement if ( Expression ) StatementFrom the looks of it no curly braces are required but we need to clarify what exactly a statement is. This syntax is found in section 12.
Statement : Block VariableStatement EmptyStatement ExpressionStatement IfStatement IterationStatement ContinueStatement BreakStatement ReturnStatement WithStatement LabelledStatement SwitchStatement ThrowStatement TryStatement DebuggerStatementIf we dig a bit deeper into section 12.1 we’ll find the definition of the block statement.
Block : { StatementListopt }We found the curly braces but does this mean they are required? The answer is no. When examining the syntax of a statement each element following the colon is considered a statement and therefore a valid part of the if statement syntax. The following are actual examples of valid if statements.