最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Javascript: false || undefined vs undefined || false - Stack Overflow

programmeradmin7浏览0评论

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

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
Share Improve this question asked Jan 26, 2014 at 19:09 Michael RadionovMichael Radionov 13.3k2 gold badges58 silver badges75 bronze badges 1
  • 1 possible duplicate of What does the || operator do? – Stephen Commented Jan 26, 2014 at 19:14
Add a comment  | 

3 Answers 3

Reset to default 15

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.

发布评论

评论列表(0)

  1. 暂无评论