If babel converts let and const to var, what's the difference?

大憨熊 提交于 2021-02-04 19:16:08

问题


I've tried the babel transpiler, and it converts All let, const and var to just var, so in all, what's the difference in our code usage?
I have read documents and I know what's the difference between let, const and var, but if all of them are eventually converted to var, what's the difference? it means that there shouldn't be any meaningful differences in performance or even scope!

Update(02.14.2019) : Based on the answers I understood that scope does matter and even though they are converted to var, babel keeps the meaning of scope. My question remains about the performance, is there any meaningful difference in performance?

I've attached the input and output of the transpiler, with a more complex scenario
input:

let a = 1;

for (let a = 0; a !== 0;) {
  for (let a = 0; a !== 0;) {}
}

output

"use strict";

var a = 1;

for (var _a = 0; _a !== 0;) {
  for (var _a2 = 0; _a2 !== 0;) {}
}

回答1:


Babel converts the ES6 syntax to ES5 syntax (or whatever source and target versions of JS you are dealing with).

This will often lose some of the nuances in the code, but you are looking at a very trivial example.

Consider this instead:

let x = 1;

{
  // Inside a block, this is a different x
  let x = 2; 
  console.log(x);
}

console.log(x);

Babel will convert that to:

"use strict";

var x = 1;
{
  // Inside a block, this is a different x
  var _x = 2;
  console.log(_x);
}
console.log(x);

See how it renames the inner x so that it doesn't overwrite the outer one?

It expresses the effect of the ES6 as much as it can in ES5, even if the result is ugly (because the elegant feature from ES6 is not available).




回答2:


Babel runs checks against each variable, and throws errors if certain procedural rules are violated. For example, if a const is defined, and the value is changed later, this would violate the type's rules. Another would be if a variable is redefined in a scope where it already exists (this could be a function of the same name). In some cases Babel simply renames things to prevent conflicts.



来源:https://stackoverflow.com/questions/54694217/if-babel-converts-let-and-const-to-var-whats-the-difference

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!