Why does babel rewrite imported function call to (0, fn)(…)?


Given an input file like

import { a } from 'b';

function x () {
  a()
}

babel will compile it to

'use strict';

var _b = require('b');

function x() {
  (0, _b.a)();
}

but when compiled in loose mode the function call is output as _b.a();

I've done some research into where the comma operator is added in the hope there was a comment explaining it. The code responsible for adding it is here.

(0, _b.a)() ensures that the function _b.a is called with this set to the global object (or if strict mode is enabled, to undefined). If you were to call _b.a() directly, then _b.a is called with this set to _b.

(0, _b.a)(); is equivalent to

0; // Ignore result
var tmp = _b.a;
tmp();

(the , is the comma operator, see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comma_Operator).


The comma operator evaluates each of its operands (from left to right) and returns the value of the last operand.

console.log((1, 2)); // Returns 2 in console
console.log((a = b = 3, c = 4)); // Returns 4 in console

So, let see an example:

var a = {
  foo: function() {
    console.log(this === window);
  }
};

a.foo(); // Returns 'false' in console
(0, a.foo)(); // Returns 'true' in console

Now, in foo method, this is equal to a (because foo is attached to a). So if you call a.foo() directly, it will log false in console.

But, if you were call (0, a.foo)(). The expression (0, a.foo) will evaluate each of its operands (from left to right) and returns the value of the last operand. In other words, (0, a.foo) is equivalent to

function() {
  console.log(this === window);
}

Since this function no longer is attached to anything, its this is the global object window. That's why it log true in console when call (0, a.foo)().