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.
Similar Posts:
- Vue Switch JS ERROR:unexpected lexical declaration in case block
- Solution to the problem of “TypeError: Assignment to constant variable”
- [Solved] A label can only be part of statement and a declaratioin is not a statement
- shadows name ‘xxxx’ from outer scope
- Error: [$compile:nonassign] Expression used with directive ‘uibTab’ is non-assignable
- [swscaler @ …] deprecated pixel format used, make sure you did set range correctly
- How to Solve Const variable assignment Error
- error C2143: syntax error : missing ‘;’ before ‘type’
- Accessors are only available when targeting ECMAScript 5 and higher [Solved]
- SyntaxError: missing ; Problem record of before statement