Javascript K combinator

const tap = (value) =>
  (fn) => (
    typeof(fn) === 'function' && fn(value),
    value
  )

this example is given in javascript allonge.
Can someone please help me with the last part

(
    typeof(fn) === 'function' && fn(value),
    value
  )

If i am correct, this returns a function with two arguments…but the function itself doesnt do anything?

tap is a function that takes one parameter value and returns a function that I’ll call the customizer function which is this arrow function referencing the closure variable value passed to tap

// customizer function returned by tap
(fn) => (
  typeof(fn) === ‘function’ && fn(value),
  value
)

the customizer takes one parameter fn and returns the result of a comma expression - the parentheses are for grouping not for function call

the input parameter fn can be anything but it’s only when fn is a callback function that anything interesting happens

the first part of the comma expression checks if fn is a callback function - if so it is called with value as the argument - if fn is not a function nothing happens

the second and last part of the comma expression is simply value which becomes the value of the comma expression - so the customizer always returns value

in a nutshell - the customizer allows the user of tap to provide a custom callback function to modify the behavior of tap

since tap returns a function this means to really use tap you always need two pairs of parentheses tap()() - the first pair is for the call to tap - the second pair is for the call to the customizer - if the second pair is empty you get the unmodified behavior of tap - if the second pair has a callback you get the callback to run plus the original behavior of tap

1 Like

Thanks for the reply that was really helpful!

You may find this post useful too - it explains how callbacks are also used for async event handing