5

I came across this in code generated by Babel from this source. It would appear to be guarding a required function, somehow.

(0, _utilities.validateNextState)(nextDomainState, reducerName, action);

I understand how the comma statement in the parenthesis discards the 0 and returns the validateNextState function, but why not just do:

_utilities.validateNextState(nextDomainState, reducerName, action);

My guess is a type of guard (like closures guard scope, or setTimeout makes a function call asynchronous), but can't figure out what it's purpose is.

nathancahill
  • 9,421
  • 8
  • 44
  • 87

1 Answers1

3

The sometimes mystifying semantics of JavaScript are probably the reason. The expression

(0, _utilities.validateNextState)

evaluates of course to a reference to that function. However, because it's in that parenthesized subexpression, the function call that's outside that will be made without that _utilities object being recognized as the context for the call (the this value). Thus inside the validateNextState function, this will be either undefined or a reference to the global object, depending on the "strict" mode state.

I suspect that Babel does that because in the original source code the call to validateNextState() is made as if it were a "naked" function, not a method on an object. Babel doesn't know (probably) whether the value of this matters to that particular function, but it has to make sure it gets invoked safely.

Pointy
  • 371,531
  • 55
  • 528
  • 584