I am going through a introductory tutorial about typescript where i have a main.ts file as
Main.ts
function dosomething(){
for(let i=0;i<3;i++)
{
console.log("i "+ i); // line a
}
console.log("Finally "+ i); //Line b
}
dosomething(); //calling the function
When I compile the file using node, the compilation step shows error cannot find i for Line b but still generates the following main.js file
Main.js
function dosomething() {
for (var i = 0; i < 3; i++) {
console.log("i " + i);
}
console.log("Finally " + i);
}
As tutorial says, typescript converts by default to ES5. That's why we got var instead of Let. and executing main.js works as expected.
My question is assuming We can also use Typescript instead of Babel,Babel converts ES6 code to ES5 which I have understood is whatever functionality we got by writing our Code in ES6 ,babel converts it into equivalent code in ES5. So let keyword will be converted to Var but with some extra code which will make this var keyword behave as let in equivalent ES5 code. So if Typescript simply converts let to var, Is it right in saying We can use typescript instead of Babel.
I am running the above main.ts snippet in babel compiler and get the following ES5 Code
Main.js
function dosomething() {
for (var _i = 0; _i < 3; _i++) {
console.log("i " + _i);
}
console.log("Finally " + i);
}
dosomething();
Notice that let variable i in for loop in main.ts has been converted to _i and and outer console.log i simply remains i.
letis block scoped inside theforloop. You cant usually access it outside of it. You should declare it outside of the loop if you want to use it there.