4

What is the explanation for behavior of the "||" operator (logical OR), when using it with false and undefined on both sides in JavaScript?

1)

> false || undefined
undefined

2)

> undefined || false
false
Michael Radionov
  • 12,859
  • 1
  • 55
  • 72
  • 1
    possible duplicate of [What does the || operator do?](http://stackoverflow.com/questions/830618/what-does-the-operator-do) – Stephen Jan 26 '14 at 19:14

3 Answers3

14

The logical OR operator isn't commutative like +, *, etc. It returns the first expression which can be converted into true. (Source Mozilla Doc)

  1. In false || undefined, false can't be converted to true by definition (since it's the opposite), so it returns the second operand (undefined)

  2. In undefined || false, undefined is a value, but considered as false in Javascript, so the logical operator evaluate the second operand and returns false (because both operands are false).

Maxime Lorant
  • 34,607
  • 19
  • 87
  • 97
  • 1
    sorry, do you have a typo in your second statement or maybe I'm not getting and there is a situation where `undefined || false` returns `undefined`? (originally should return `false`) – Michael Radionov Jan 26 '14 at 20:32
  • yeah indeed. I have mixed my ideas when I was writing I guess. I've fixed this. – Maxime Lorant Jan 26 '14 at 20:40
3

According to Logical Operators in Mozilla Docs:

Logical OR (||)

expr1 || expr2

Returns 'expr1' if it can be converted to true; otherwise, returns 'expr2.

1) in case false || undefined: false(expr1) can not be converted to true, so undefined(expr2) is returned

2) in case undefined || false: undefined(expr1) can not be converted to true, so false(expr2) is returned

Michael Radionov
  • 12,859
  • 1
  • 55
  • 72
3

This question is not related particularly to just false and undefined but, to any of the Falsy Values in Javascript. Note that there are a total of six falsy values in Javascript:

  • false.
  • 0 (zero)
  • '' or "" (an empty string)
  • null
  • undefined
  • NaN

When you run the logical OR operation between two Falsy Values, say <left value> || <right value> in JS, it always returns the value on the right side of the OR operator. Reason being that the OR operator, as per its implementation in ECMAScript Engines, in general returns the left value if it can be coerced to true. But, if the value on the left side of the operator cannot be coerced to true, the right value is always returned no matter what the value on the right is, instead of getting coerced as one might expect.

UtkarshPramodGupta
  • 7,486
  • 7
  • 30
  • 54