Why does TypeScript when compiled, convert "let" to "var" in variables?

4

If let variavel = "valor"; is also supported in JavaScript , because in TypeScript compilation, it transforms to var variavel = "valor" ?

Take the test right here :

function foo(){
  var x = 1;
  let y = 3;
  if (true){
    var x = 2;
    let y = 4;
    console.log(x); //Irá resultar 2.
    console.log(y); //Irá resultar 4.
  }
  console.log(x); //Irá resultar 2 porque o escopo do 'var' abrangiu toda a função foo().
  console.log(y); //Irá resultar 3 porque o escopo do 'let' abrangiu apenas o bloco, diferente da atribuição na expressão if.
}
    
asked by anonymous 20.08.2018 / 22:14

1 answer

4

I can not respond in an authoritative way in specific, but from what I know of compilation and transpilation , it makes some sense because the extra control that let gives is the scope, which the TypeScript compiler has already ensured is appropriate, so you do not have to send something to JS for it to check again. Once it knows it is in the right scope, when JavaScript code is generated there is no reason for the JS compiler to take care of this. It would be a redundant compilation job. I imagine compiling var in JS is faster than compiling let .

The JS code generated by TS does not have to be robust, it does not have to be readable, it's not for humans, it needs to be efficient and well-made to work properly, it's another level of abstraction.

In fact it can be seen that it protects the variable by changing its name where it has let :

function foo() {
    var x = 1;
    var y = 3;
    if (true) {
        var x = 2;
        var y_1 = 4;
        console.log(x);
        console.log(y_1);
    }
    console.log(x);
    console.log(y);
}

See running and transpiling on TypeScript Playground . I also put it in GitHub for future reference .

Additionally using var ensures that it runs on older browsers that do not have let .

    
20.08.2018 / 22:28