The ES6 code:
let foo = 'outer';
function bar(func = x => foo){
let foo = 'inner';
console.log(func());
}
bar(); // outer
The Result is "outer".
The ES5 code compiled by Babel.js:
'use strict';
var foo = 'outer';
function bar() {
var func = arguments.length <= 0 || arguments[0] === undefined ? function (x) {
return foo;
} : arguments[0];
var foo = 'inner';
console.log(func());
}
bar(); // inner
The Result is "outer".
I don't know why they have different result.
Is there any feature in Babel to transpile ES5 code into ES6? Any ES5 code is valid ES6 code. And Babel only transpiles newer features into older equivalent code, not the other way round (detecting patterns in ES5 that could be expressed differently in ES6). You should aim to write ES6 as the source.
Babel is a JavaScript compiler.
Babel is a tool that lets you write your Javascript code using all the latest syntax and features, and run it in browsers that may not support those features. Babel is a transpiler that will translate your modern JS code into an older version of Javscript that more browsers are able to understand.
Babel is a very famous transpiler that basically allows us to use future JavaScript in today's browsers. In simple words, it can convert the latest version of JavaScript code into the one that the browser understands.
It's a bug in Babel. Expressions in complex parameter lists should not be able to see declarations in the body of the function, but the code generated by Babel here evaluates the default parameter in the scope of the function, where the inner foo
is visible.
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