let in if without braces

2019-01-20 12:43发布

问题:

if (true) {
  let x = 5
}

works as expected (no syntax error), but

if (true) let x = 5

throws SyntaxError: Unexpected strict mode reserved word in Node 4.1.0 and babel

Is this expected behavior? I know that this is a stupid example. I'm just wondering wether this is a bug or not.

回答1:

Yes it is expected behavior. The production rule of an if statement is

 if ( Expression[In, ?Yield] ) Statement[?Yield, ?Return]

but a let declaration is not a Statement and is therefore not allowed in this position:

Statement[Yield, Return] :
    BlockStatement[?Yield, ?Return]
    VariableStatement[?Yield]
    EmptyStatement
    ExpressionStatement[?Yield]
    IfStatement[?Yield, ?Return]
    BreakableStatement[?Yield, ?Return]
    ContinueStatement[?Yield]
    BreakStatement[?Yield]
    [+Return] ReturnStatement[?Yield]
    WithStatement[?Yield, ?Return]
    LabelledStatement[?Yield, ?Return]
    ThrowStatement[?Yield]
    TryStatement[?Yield, ?Return]
    DebuggerStatement

Declaration[Yield] :
    HoistableDeclaration[?Yield]
    ClassDeclaration[?Yield]
    LexicalDeclaration[In, ?Yield]

LexicalDeclaration[In, Yield] :
    LetOrConst BindingList[?In, ?Yield] ;