0

I understand a||b returns an object, not boolean value. I just can't figure out why javascript gives different results for

undefined || "" (result is "")
"" || undefined (result is undefined)

which I think both should return "". Can someone explain it to me? Thanks!

Update: it is answered clearly by @Quentin, "" is evaluated as false, and a||b will return b if both a and b are evaluated as false.

AlliceSmash
  • 687
  • 1
  • 11
  • 19

3 Answers3

5

The || operator tests the truthiness of the left hand side of the expression. If the LHS is a true value, then it returns the LHS, otherwise it returns the RHS.

You can see how this combines with an if for a practical example:

if (a || b)
  • If a is true, then it is the same as if (a) which is if (true).
  • If a is false and b is true, then if (b) is if (true)
  • If a and b are both false, then it is if (b) which is if (false)

If your example, neither "" nor undefined are true values, so both of your tests will return the RHS.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
3

JavaScript's logical OR operator, ||, returns one of its operands. In a || b, it returns a if a is truthy, and b otherwise.

Both of your arguments evaluate as false. So in undefined || "", it returns "". For "" || undefined, it returns undefined. In both cases, it's because that's what's in the b position.

Alex P
  • 5,942
  • 2
  • 23
  • 30
1

The || operator returns the first argument that evaluates as true. If all the arguments are false then it just returns the last argument, whatever it may be.

user1958756
  • 377
  • 1
  • 4
  • 17