Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the purpose of calling (0, func)() in JS? [duplicate]

Tags:

javascript

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.

like image 530
nathancahill Avatar asked Oct 17 '22 03:10

nathancahill


1 Answers

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.

like image 84
Pointy Avatar answered Oct 21 '22 08:10

Pointy