Logical OR

The logical OR operator is || in JavaScript:


var result = true || false;

Logical OR behaves in the following truth table:

OPERAND 1OPERAND 2RESULT
truetruetrue
truefalsetrue
falsetruetrue
falsefalsefalse

When logical OR working with non-Boolean values:

OPERAND 1OPERAND 2RESULT
objectany valuereturn the first operand
falseany valuereturn OPERAND 2
objectobjectreturn the first operand
nullnullnull
NaNNaNNaN
undefinedundefinedundefined

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>
  
Click to view the demo

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  

Operators:
  1. JavaScript Operators
  2. Increment/Decrement Operators
  3. Increment/Decrement Operators for String, Boolean, Floating-point and Object
  4. Unary Plus and Minus
  5. Bitwise Not operator
  6. Bitwise AND
  7. Bitwise OR
  8. Bitwise XOR
  9. Left Shift
  10. Signed Right Shift
  11. Unsigned Right Shift
  12. Logical NOT
  13. Logical AND
  14. Logical OR
  15. Multiply
  16. Divide
  17. Modulus
  18. Add
  19. Subtract
  20. Relational Operators
  21. Equal and Not Equal
  22. Identically Equal and Not Identically Equal
  23. Conditional Operator
  24. Assignment Operators
  25. Comma Operator