Typescript Deep Dive by Basarat Ali Syed
Typescript Deep Dive by Basarat Ali Syed
Typescript Deep Dive by Basarat Ali Syed
Create successful ePaper yourself
Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.
TypeScript <strong>Deep</strong> <strong>Dive</strong><br />
}<br />
Here the functions close over (hence called a closure ) the local variable (conveniently named local ) and use that instead<br />
of the loop variable i . Note that closures come with a performance impact (they need to store the surrounding state) and<br />
therefore even though the ES6 let keyword in a loop would have the same behavior as the previous example, the<br />
following is an error in TypeScript if you target something less than ES6:<br />
var funcs = [];<br />
// create a bunch of functions<br />
for (let i = 0; i < 3; i++) {<br />
// Error: Loop contains block-scoped variable 'i' referenced <strong>by</strong> a function in the loop.<br />
// This is only supported in ECMAScript 6 or higher.<br />
funcs.push(function() {<br />
console.log(i);<br />
})<br />
}<br />
// call them<br />
for (var j = 0; j < 3; j++) {<br />
funcs[j]();<br />
}<br />
Note: This limitation may be removed in a future version of TypeScript.<br />
Summary<br />
Despite a few limitations, we find let to be extremely useful to have for the vast majority of code. It can greatly enhance<br />
your code readability and decrease the chance of a programming error.<br />
Fork me on github<br />
let<br />
25