Code 1
if (true) {
var x = 1;
}
Code 2
if (true)
var x = 1;
Code 3
if (true) {
let x = 1;
}
Code 4
if (true)
var x = 1;
For the above four codes, Code 4 reports the error “Lexical declaration cannot appear in a single-statement context”, to which TypeScript author Anders Hejlsberg says:
JavaScript only permits let and const declarations within a block
Github Issue
Someone Said:
https://www.ecma-international.org/ecma-262/6.0/#sec-let-and-const-declarations let and const declarations define variables that are scoped to the running execution context’s LexicalEnvironment. https://www.ecma-international.org/ecma-262/6.0/#sec-lexical-environments A Lexical Environment consists of an Environment Record and a possibly null reference to an outer Lexical Environment. Usually a Lexical Environment is associated with some specific syntactic structure of ECMAScript code such as a FunctionDeclaration, a BlockStatement, or a Catch clause of a TryStatement and a new Lexical Environment is created each time such code is evaluated. https://www.ecma-international.org/ecma-262/6.0/#sec-declarative-environment-records Each declarative Environment Record is associated with an ECMAScript program scope containing variable, constant, let, class, module, import, and/or function declarations.
Thinking about it, it’s perfectly possible for a JavaScript engine to treat this case as declaring a variable in a block scope, but that doesn’t make sense, because in this case declaring a variable on a single line with a let must not use the variable anywhere, and if it did, it would have to explicitly indicate a block scope using curly braces.