Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why the ES6 code and ES5 code has diffent result after compiling by Babel.js?

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.

like image 516
ccforward Avatar asked Jul 21 '16 02:07

ccforward


People also ask

Can Babel convert ES5 to ES6?

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.

Is Babel a compiler or transpiler?

Babel is a JavaScript compiler.

How does Babel JS work?

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.

Why do we need Babel?

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.


1 Answers

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.

like image 94
Bakkot Avatar answered Oct 06 '22 01:10

Bakkot