Friday, April 14, 2017

The let keyword in TypeScript is pretty good about keeping immediate lexical scope from affecting parent scope.

let foo = 123;
if (true) {
   let foo = 456;
}
alert(foo);

...returns 123, while...

 
 

var foo = 123;
if (true) {
   var foo = 456;
}
alert(foo);

...returns 456 (not cool). The let trick works by making JavaScript like so:

 
 

var foo = 123;
if (true) {
   var foo_1 = 456;
}
alert(foo);

By the way, as a bonus...

 
 

var foo = 123;
var bar = {
   baz: foo
};
alert(bar.baz);
foo = 456;
alert(bar.baz);

...gives 123 twice.

No comments:

Post a Comment