0

I saw this React onClick handler:

onClick={backToPreviousPage || (() => window.history.back())}

And I can't exactly figure out the logic of the || operator inside this click handler and what does it accomplish. Which function would actually execute on the click if both are defined. Does it tries to execute backToPreviousPage first, and then window.history.back() if backToPreviousPage is not defined?

Onyx
  • 5,186
  • 8
  • 39
  • 86
  • 2
    See the linked questions for details. JavaScript's `||` is (as I say in [this post](http://blog.niftysnippets.org/2008/02/javascripts-curiously-powerful-or.html)) curiously powerful. Instead of resulting in `true` or `false`, it results in the value of one of its operands. When evaluating `a || b`, `a` is evaluated and if the result is *truthy*, that value is used as the result of the `||`. If the result of evaluating `a` is *falsy*, `b` is evaluated and that result is used as the result of the `||`. So in the code you've shown, if `backToPreviousPage` has a truthy value, that's... – T.J. Crowder Jun 07 '21 at 12:53
  • 1
    ...used; otherwise, `(() => window.history.back())` is evaluated (creating a function) and used. *"Does it tries to execute `backToPreviousPage` first"* No, because there are no `()` after `backToPreviousPage`. It uses the function object, it doesn't **call** the function. – T.J. Crowder Jun 07 '21 at 12:54
  • 1
    *"falsy"* = is considered `false` in conditions. The falsy values are `0`, `""`, `NaN`, `null`, `undefined`, and of course `false` (also, bizarrely, `document.all` on browsers). All other values are *truthy*. – T.J. Crowder Jun 07 '21 at 12:55
  • @T.J.Crowder Thank you, I was relatively confused because I've never used the OR operator in such a way. – Onyx Jun 07 '21 at 13:08
  • 1
    My pleasure! I should have noted that in modern code you'd probably see `??` in that situation instead (the [nullish coalescing operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_operator)) (`backtoPreviousPage` is probably `null` or `undefined` when it's falsy). `||` was often used for this before `??` was added (fairly recently). – T.J. Crowder Jun 07 '21 at 13:10

0 Answers0