The logical OR operator is || and it operates on two values.
var result = true || false;
Logical OR behaves as described in the following truth table:
Operand 1 | Operand 2 | Result |
---|---|---|
true | true | true |
true | false | true |
false | true | true |
false | false | false |
If either operand is not a Boolean, logical OR will not always return a Boolean value.
OR operator follows the following rules:
first OR second | Result |
---|---|
the first operand is an object | the first operand is returned. |
the first operand evaluates to false | the second operand is returned. |
both operands are objects | the first operand is returned. |
both operands are null | null is returned. |
both operands are NaN | NaN is returned. |
both operands are undefined | undefined is returned. |
The logical OR operator is short-circuited.
In this case, if the first operand evaluates to true, the second operand is not evaluated.
You can use short-circuited behavior to avoid assigning a null or undefined value to a variable. Consider the following:
var myObject = preferredObject || backupObject;
myObject will be assigned one of two values.
If preferredObject isn't null, then it's assigned to myObject.
If it is null, then backupObject is assigned to myObject.