skip to Main Content

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


  1. The return value of alert('first') is being passed as the second argument to Array#map, so it is evaluated before map is called.

    In this case, the second parameter of map is the value to set as this of the callback. Note that you can also pass arguments that a function is not even declared to take as parameters.

    Login or Signup to reply.
  2. 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

    .map(
       (fx) => fx && fx !== true && (fx[0] || fx)(dispatch, fx[1]),
       update(action[0])
    )
    

    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 effect

    So 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)

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search