2

I'm trying to understand the libraries used in this article and elsewhere, and there's some pretty mind bending stuff in there, among which is the line

(0, _invariant2.default)(opts.hasOwnProperty('apiKey'), 'You must pass an apiKey to use GoogleApi');

Searching GitHub shows this piece of code, or variations on it, has been reproduced in loads of projects (although I can't find where it originated).

I can see that it boils down to a call to a function named invariant, but what I don't understand is the purpose of the comma operator with zero here.

Why not just write

_invariant2.default(opts.hasOwnProperty('apiKey'), 'You must pass an apiKey to use GoogleApi')
Alex
  • 1,061
  • 2
  • 11
  • 19
  • See this http://stackoverflow.com/questions/6577812/calling-function-with-window-scope-explanation-0-function for explanations – Mathias Nater May 11 '17 at 08:40
  • Which still leaves the question of "what's the point?". It's a very unreliable way of setting *this* to the global object since if run in strict mode, *this* will be undefined. It seems to pre-date strict mode though. – RobG May 11 '17 at 08:49
  • @RobG It's the transpiled result of [this code](https://github.com/fullstackreact/google-maps-react/blob/cd4534e41c36b1d57b00b40e8a06143a07c270eb/src/lib/GoogleApi.js#L6-L7). The imported `invariant` is a function that needs to be called without a context, so to prevent `this` being set to `_invariant2` (whatever that may be), the context is stripped off. – robertklep May 11 '17 at 09:04
  • @robertklep Thanks for posting the link to the original code. I did wonder whether the code might be machine generated, but I wasn't sure. – Alex May 11 '17 at 09:45
  • @robertklep—I'm OK with the explanation, but not why it persists as a meme. The end result is that the value of *this* is unreliable, so clearly the called function doesn't care, so why bother even trying to set it to *global* or *undefined* because it can't matter. And if it did, then `foo.call(window, ...)` is a much better way to do it. ;-) – RobG May 11 '17 at 10:02
  • @RobG as mentioned [here](http://stackoverflow.com/questions/32275135/why-does-babel-rewrite-imported-function-call-to-0-fn#comment65733980_32275135), `(0, foo)(...)` is shorter than `foo.call(context, ...)` ;D – robertklep May 11 '17 at 10:06

0 Answers0