let declarations

In JavaScript, var declarations are “hoisted” to the top of their enclosing scope. This can result in confusing bugs:

  1. console.log(x); // meant to write 'y' here
  2. /* later in the same block */
  3. 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:

  1. if (foo) {
  2. console.log(x); // Error, cannot refer to x before its declaration
  3. let x = 'hello';
  4. }
  5. else {
  6. console.log(x); // Error, x is not declared in this block
  7. }

let is only available when targeting ECMAScript 6 (—target ES6).