Reputation: 523
I was taking a look at AngularJS 2 and Typescript and I decided to make something with this just to learn the basics of Typescript. With many research I found good topics about modules, Typescript, and one of them was talking about the 'let' and 'var' command to declare variables; according to this question, the Typescript code below should display only one alert and throw an error in the console:
test.ts:
for(let i = 0; i < 1; i++) {
alert(i);
}
alert(i);
Compiled test.js:
for(var i = 0; i < 1; i++) {
alert(i);
}
alert(i);
//# sourceMappingURL=test.js.map
But it isn't. The compiler "ignores" the "let" command and turns it into the "var" command. Why does this happen? Does Typescript only works properly with classes?
I'm using AngularJS configuration for 'npm start', so it compiles my 'test.ts' file automatically:
"scripts": {
"start": "tsc && concurrently \"npm run tsc:w\" \"npm run lite\" ",
"lite": "lite-server",
"postinstall": "typings install",
"tsc": "tsc",
"tsc:w": "tsc -w",
"typings": "typings"
},
Upvotes: 12
Views: 13475
Reputation: 19193
In this example, var
and let
have the same effect, with var
being a little faster on most JS engines, so TypeScript does some performances optimization for you by changing that to a var
.
Now if you try a different example, you will see that let
isn't just changed into var
, but more magic happens:
for (let i = 0; i < 3; i++) {
setTimeout(function() { alert(i); });
}
Indeed in this example let
and var
wouldn't have the same effect. let
would display 1 2 3
while using var
we would see 3 3 3
. If you want to learn more about the let
keyword introduced by ES6 you can check this:
https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Instructions/let
Upvotes: 2
Reputation: 106690
But it isn't. The compiler "ignores" the "let" command and turns it into the "var" command. Why does this happen? Does Typescript only works properly with classes?
The compiler by default transpiles to ES3. The let
keyword doesn't exist in ES3 and so the emitter must emit code using syntax available in ES3... in this case the best replacement for the let
keyword is the var
keyword.
If you want it to emit with the let
keyword, then you must target ES6—"target": "es6"
in tsconfig.json or the command line option --target es6
. Doing this will output with the same code that you inputted.
Note that even though your code works at runtime, it throws an error to let you know you have made a mistake at compile time:
for(let i = 0; i < 1; i++) {
alert(i);
}
alert(i); // compile error: cannot find name 'i'
Upvotes: 25
Reputation: 4552
They are identical but there is a difference when they used inside a function.
LET
function theDifference(){
for(let emre = 0; emre < 10; emre++){
// emre is only visible inside of this for()
}
// emre is NOT visible here.
}
VAR
function theDifference(){
for(var emre = 0; emre < 10; emre++){
// emre is visible inside of this for()
}
// emre is visible here too.
}
Upvotes: 0