1

Is there some functional programming rule that says that these two things are the same?

That is, I'm passing a function as a attribute in a React program and I was using the second version with the first parameter passed in. Just out of curiosity, I replaced with just passing the function and my app still worked but I'm confused why.

(to be extra clear, onFavoriteToggle is a function)

  <SpeakerFavorite
    favorite={favorite}
    onFavoriteToggle={onFavoriteToggle}
  />

compared to

  <SpeakerFavorite
      favorite={favorite}
      onFavoriteToggle={(fun) => {onFavoriteToggle(fun)}}
  />
 
Peter Kellner
  • 14,748
  • 25
  • 102
  • 188
  • 1
    Does this answer your question? [How to decide when to pass parameter & when not](https://stackoverflow.com/questions/63632290/how-to-decide-when-to-pass-parameter-when-not) – jonrsharpe Mar 04 '21 at 13:40
  • And what do you mean by *"functional programming rule"*? – jonrsharpe Mar 04 '21 at 13:41
  • [Yes, as long as `onFavoriteToggle()` takes only one parameter and it's going to be called with only one parameter, then eta reduction makes them equal](https://stackoverflow.com/a/59878788/) – VLAZ Mar 04 '21 at 13:48
  • @VLAZ, Does my example fall under the category of Identity functions? I know without the parameter it does, not sure if with the parameter is the same. – Peter Kellner Mar 04 '21 at 13:51
  • No, it's not an identity. An identity function has different semantics - it's `x => x`. However, with equal parameters, `x => fn(x)` is reducible to just `fn`. For example, `["1", "2", "3"].map(x => Number(x))` is the same as `["1", "2", "3"].map(Number)`. However, `["1", "2", "3"].map(x => parseInt(x))` is *not* the same as ["1", "2", "3"].map(parseInt)` because because of the different arity of the function and how it's going to be called. See [Why does parseInt yield NaN with Array#map?](https://stackoverflow.com/q/262427) – VLAZ Mar 04 '21 at 13:58
  • These _can_ be equivalent but are not universally so. For example if the example is actually `this` specific, if the function takes a number of arguments etc. To avoid ambiguity and problems when underlying interfaces change, I would advise against the first option. – Etheryte Mar 04 '21 at 13:59

1 Answers1

0
(fun) => {onFavoriteToggle(fun)}

is a "proxy" function that simply calls another function with the same argument it receives. In this case, serves no purpose and actually may harm your app performance in extreme cases.

However, if SpeakerFavorite calls this "proxy" function passed as onFavoriteToggle prop with not one, but two arguments, the second argument would now get lost, as "proxy" function only receives one argument. This may lead to hard to debug errors.

If you don't need to do anything else, just pass the function without "proxy" in between.

Wojciech Maj
  • 982
  • 6
  • 21