Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compiling ES6 arrow functions to Es5 using Babel.js



While looking into ES6 arrow functions' documentation on Mozilla documentation, I got to know that Arrow functions applies all the rules of strict mode, except one as described in the link

  var f = () => { 'use strict'; return this};
    var g = function () { 'use strict'; return this;}

    console.log(f()); //prints Window
    console.log(g()); // prints undefined

    //we can test this in firefox!

But, Babel.jsis transpiling the arrow function code to ES5 code that returns undefined rather than Window(demo link)

"use strict";

setTimeout(function () {
  return undefined;
}, 100);

So, the above snippet is the output from Babel.js. Couldn't it be the below output?

"use strict";

setTimeout(function () {
  return this;
}.bind(Window), 100);

If I am writing ES6, I would expect Window rather than undefined
Is it a bug?
OR, I misunderstood anything?

like image 758
Navaneeth Avatar asked Jun 08 '15 06:06

Navaneeth


People also ask

Does Babel compile ES6 to ES5?

Babel is a transpiler because it translates JavaScript ES6 to JavaScript ES5. In contrast, a compiler translates source code from a higher level language to a lower level.

Does ES5 have arrow functions?

The arrow function concept was introduced in ES6. With the help of this, we can write a shorter and concise syntax for a normal function which we used to write in ES5. Note: In arrow function, if there is only one statement then we don't even need to use '{}' curly braces.

Which tool is used to convert ES6 to ES5 and how does it convert the following function?

BabelJS - ES5 There is extra code added using babeljs to get the functionality working for classes same as in ES5. BabelJs makes sure the functionality works same as it would have done in ES6.


1 Answers

tl;dr: Babel assumes every file is a module. Modules are strict by default and their this value is undefined.


This is covered in the Babel FAQ:

Babel assumes that all input code is an ES2015 module. ES2015 modules are implicitly strict mode so this means that top-level this is not window in the browser nor is it exports in node.

If you don't want this behaviour then you have the option of disabling the strict transformer:

$ babel --blacklist strict script.js

require("babel").transform("code", { blacklist: ["strict"] });

PLEASE NOTE: If you do this you're willingly deviating from the spec and this may cause future interop issues.

See the strict transformer docs for more info.

like image 73
Felix Kling Avatar answered Sep 30 '22 10:09

Felix Kling