Reputation: 71
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.
Upvotes: 6
Views: 81
Reputation: 1245
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.
Upvotes: 5