Javascript: false || undefined vs undefined || false

狂风中的少年 提交于 2019-12-05 12:05:40

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).

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

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!