Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: false || undefined vs undefined || 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
like image 361
Michael Radionov Avatar asked Dec 03 '22 20:12

Michael Radionov


1 Answers

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

like image 71
Maxime Lorant Avatar answered Dec 13 '22 10:12

Maxime Lorant