Logical OR
The logical OR operator is || in JavaScript:
var result = true || false;
Logical OR behaves in the following truth table:
OPERAND 1 | OPERAND 2 | RESULT |
---|---|---|
true | true | true |
true | false | true |
false | true | true |
false | false | false |
When logical OR working with non-Boolean values:
OPERAND 1 | OPERAND 2 | RESULT |
---|---|---|
object | any value | return the first operand |
false | any value | return OPERAND 2 |
object | object | return the first operand |
null | null | null |
NaN | NaN | NaN |
undefined | undefined | undefined |
The logical OR operator is short-circuited. The short-circuited operation means that if the first operand determines the result, the second operand is not evaluated. If the first operand evaluates to true, the second operand is not evaluated.
<!DOCTYPE html>
<html>
<head>
<title>Example</title>
<script type="text/javascript">
var found = true;
var i=1;
var result = found || i++;
document.writeln(result); //true
found = false;
var result = found || i++;
document.writeln(result); //1
document.writeln(i); //2
var result = found || i++;
document.writeln(result); //2
document.writeln(i); //3
</script>
</head>
<body>
</body>
</html>
You can use short-circuited OR operator to avoid assigning a null or undefined value to a variable.
var myObject = preferredObject || backupObject;
If preferredObject isn't null, then it's assigned to myObject; if preferredObject is null, then backupObject is assigned to myObject.
Home
JavaScript Book
Language Basics
JavaScript Book
Language Basics
Operators:
- JavaScript Operators
- Increment/Decrement Operators
- Increment/Decrement Operators for String, Boolean, Floating-point and Object
- Unary Plus and Minus
- Bitwise Not operator
- Bitwise AND
- Bitwise OR
- Bitwise XOR
- Left Shift
- Signed Right Shift
- Unsigned Right Shift
- Logical NOT
- Logical AND
- Logical OR
- Multiply
- Divide
- Modulus
- Add
- Subtract
- Relational Operators
- Equal and Not Equal
- Identically Equal and Not Identically Equal
- Conditional Operator
- Assignment Operators
- Comma Operator