The logical OR operator is represented by the double pipe (||) in Javascript:
let result = true || false;
Logical OR behaves as 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.
It does one of the following:
Like the logical AND operator, the logical OR operator is short-circuited.
If the first operand evaluates to true, the second operand is not evaluated.
Consider this example:
let found = true; let result = (found || someUndeclaredVariable); // no error console.log(result); // works
The variable someUndefinedVariable
is undefined.
Because the variable found is set to true, the variable someUndefinedVariable
is never evaluated and thus the output is "true".
If the value of found is changed to false, an error occurs, as in the following example:
let found = false; let result = (found || someUndeclaredVariable); // error occurs here console.log(result); // this line never executes
We can use this behavior to avoid assigning a null or undefined value to a variable.
Consider the following:
let myObject = preferredObject || backupObject;
In this example, the variable myObject
will be assigned one of two values.
The preferredObject
variable contains the value that is preferred if it's available.
The backupObject
variable contains the backup value if the preferred one isn't available.
If preferredObject
isn't null, then it's assigned to myObject
.
If it is null, then backupObject
is assigned to myObject
.
This pattern is used very frequently in Javascript for variable assignment.