I am trying to understand some confusing code I came across (original)
Here is a simplified version:
[1,2,3].map(v => alert(v), alert('first'))
Why is ‘first’ shows first ? and why is it evaluated only once ?
I am trying to understand some confusing code I came across (original)
Here is a simplified version:
[1,2,3].map(v => alert(v), alert('first'))
Why is ‘first’ shows first ? and why is it evaluated only once ?
2
Answers
The return value of
alert('first')
is being passed as the second argument toArray#map
, so it is evaluated beforemap
is called.In this case, the second parameter of
map
is the value to set asthis
of the callback. Note that you can also pass arguments that a function is not even declared to take as parameters.Your simplification makes it hard to explain the code since it does not make sense when using alerts.
The code in the link is using
map(callbackFn, thisArg)
Here is the original
so callback is
(fx) => fx && fx !== true && (fx[0] || fx)(dispatch, fx[1])
and thisArg is
update(action[0])
– which is possibly running as a side effectSo if the item in the array the map is run over is truthy and is not strictly equal to
true
, then if the first item is truthy, use it as a function to call with parameters dispatch and the second item in the fx array, else us the item itself as a function and call it with dispatch and undefined (since fx[1] will not exist)