I understand that ES6 and TypeScript both support block level scoping, but when targeting ES3 and ES5 the output should be function level scoping. I think there has to be a logic behind why TypeScript isn't hoisting variables.. and I'm not running into a problem, I'm more just curious why it doesn't hoist variables.
For example, given the following TypeScript:
function seed(length: number, multiplier: number): number[] {
let result: number[] = [];
for(let i: number = 0; i < length; i++) {
let n: number = i * multiplier;
result.push(n);
}
return result;
}
The transpiler outputs:
function seed(length, multiplier) {
var result = [];
for (var i = 0; i < length; i++) {
var n = i * multiplier;
result.push(n);
}
return result;
}
The result I would have expected would be one with the variable declarations hoisted to the top of the function. Looking something like this:
function seed(length, multiplier) {
var
i, n,
result = [];
for (i = 0; i < length; i++) {
n = i * multiplier;
result.push(n);
}
return result;
}
Any insight is greatly appreciated. Thanks!
It's because the compiler doesn't output code based on a coding standard. It tries to be as close as possible to the original input.
Note that var variables are hoisted behind the scenes anyway (var hoisting). There's not a need for the TypeScript compiler to change the input in this case and doing so would needlessly increase its complexity.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With