let declarations
In JavaScript, var
declarations are “hoisted” to the top of their enclosing scope. This can result in confusing bugs:
console.log(x); // meant to write 'y' here
/* later in the same block */
var x = 'hello';
The new ES6 keyword let
, now supported in TypeScript, declares a variable with more intuitive “block” semantics. A let
variable can only be referred to after its declaration, and is scoped to the syntactic block where it is defined:
if (foo) {
console.log(x); // Error, cannot refer to x before its declaration
let x = 'hello';
}
else {
console.log(x); // Error, x is not declared in this block
}
let
is only available when targeting ECMAScript 6 (—target ES6
).