1

I was learning mobx, and found some simple mobx code that I wanted to run in NodeJS, so I figured out how to do that using https://www.codementor.io/iykyvic/writing-your-nodejs-apps-using-es6-6dh0edw2o.

The mobx code is: (See https://babeljs.io/repl) to try it yourself.

import {observable, autorun} from 'mobx';

let cart = observable({
    itemCount: 0,
    modified: new Date()
});

autorun(() => {
    console.log(`The Cart contains ${cart.itemCount} item(s).`);
});

cart.itemCount++;

After I run babel to convert it so it can run in node, the syntax is:

"use strict";

var _mobx = require("mobx");

var cart = (0, _mobx.observable)({
  itemCount: 0,
  modified: new Date()
});
(0, _mobx.autorun)(function () {
  console.log("The Cart contains ".concat(cart.itemCount, " item(s)."));
});
cart.itemCount++;

So what does this syntax mean? (0, _mobx.autorun)( { } )

And please just don't tell me it runs the autorun function because I understand that. I'm trying to understand what the syntax (0, foo) ( ... ) means where foo is a function.

Why does babel choose to do that vs just calling the function?

I'm guessing it's similar to the reason ('a', 'b', 'c', 1) evaluates to 1.

This is just a curiosity question, so don't overthink it.

Note: (0,console.log)('hi') prints 'hi' as does (1,console.log)('hi')

PatS
  • 8,833
  • 12
  • 57
  • 100
  • `(0, foo)()` evaluates to `(0, foo)` first. The comma operator evaluates to its RHS, so `foo`. Thus you'll have `foo()`. It has the added effect of removing the calling context of `foo` – Andrew Li Aug 05 '19 at 23:01

0 Answers0