How to use Boolean Operator OR in Javascript

Description

The Boolean Operator OR is represented by the double pipe || in Javascript, like this:

var result = true || false;

OR behaves as described in the following truth table:

OPERAND 1OPERAND 2RESULT
truetruetrue
truefalsetrue
falsetruetrue
falsefalsefalse

If either operand is not a Boolean, logical OR will not always return a Boolean value; instead, it does one of the following:

  • If the first operand is an object, then the first operand is returned.
  • If the first operand evaluates to false, then the second operand is returned.
  • If both operands are objects, then the first operand is returned.
  • If both operands are null, then null is returned.
  • If both operands are NaN, then NaN is returned.
  • If both operands are undefined, then undefined is returned.

OR operator is short-circuited. In this case, if the first operand evaluates to true, the second operand is not evaluated.


var found = true;
var result = (found || someUndeclaredVariable);    //no error
console.log(result);    //works

found = false;
var result = (found || someUndeclaredVariable);    //error occurs here
console.log(result);    //this line never executes

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 will occur.

Example

To avoid assigning a null or undefined value to a variable, use the following code.

var myObject = preferredObject || backupObject;

If preferredObject isn't null, then it's assigned to myObject; if it is null, then backupObject is assigned to myObject.





















Home »
  Javascript »
    Javascript Introduction »




Script Element
Syntax
Data Type
Operator
Statement
Array
Primitive Wrapper Types
Function
Object-Oriented
Date
DOM
JSON
Regular Expressions