Search code examples
javascriptconditional-statementsconditional-operator

Unexpected result when falling back to a ternary operator from and OR in Javascript


Can anyone of you incredible and wise developers out there tell me why

"yes" || true === true ? "no" : null

returns "no"

but

"yes" || (true === true ? "no" : null)

returns "yes"?

It's stumped me!


Solution

  • The OR operator (||) is a short-circuit operator, so as soon as it finds a truthy value, it returns it. In the second case, you've got two values, "yes", and everything inside the parens. Since "yes", a non-empty string, is truthy, it will short circuit to return that.

    In your first case, everything before the ? is implicitly grouped together, so it's the same as saying ("yes" || true === true) ? "no" : null. Since ("yes" || true === true) evaluates to truthy, we'll get the affirmative option of the ternary, "no".