Skip to content

2.11 Logical operators

Bunlong VAN edited this page Feb 16, 2018 · 2 revisions

There are three logical operators in JavaScript: || (OR), && (AND), ! (NOT).

Although they are called “logical”, they can be applied to values of any type, not only boolean. The result can also be of any type.

Let’s see the details.

|| (OR)

The “OR” operator is represented with two vertical line symbols:

result = a || b;

In classical programming, logical OR is meant to manipulate boolean values only. If any of its arguments are true, then it returns true, otherwise it returns false.

In JavaScript the operator is a little bit more tricky and powerful. But first let’s see what happens with boolean values.

There are four possible logical combinations:

alert( true || true );   // true
alert( false || true );  // true
alert( true || false );  // true
alert( false || false ); // false

As we can see, the result is always true except for the case when both operands are false.

If an operand is not boolean, then it’s converted to boolean for the evaluation.

For instance, a number 1 is treated as true, a number 0– as false:

if (1 || 0) { // works just like if( true || false )
  alert( 'truthy!' );
}

Most of the time, OR || is used in an if statement to test if any of the given conditions is correct.

For example:

let hour = 9;

if (hour < 10 || hour > 18) {
  alert( 'The office is closed.' );
}

We can pass more conditions:

let hour = 12;
let isWeekend = true;

if (hour < 10 || hour > 18 || isWeekend) {
  alert( 'The office is closed.' ); // it is the weekend
}

OR seeks the first truthy value

The logic described above is somewhat classical. Now let’s bring in the “extra” features of JavaScript.

The extended algorithm works as follows.

Given multiple OR’ed values:

result = value1 || value2 || value3;

The OR "||" operator does the following:

  • Evaluate operands from left to right.

  • For each operand, convert it to boolean. If the result is true, then stop and return the original value of that operand.

  • If all other operands have been assessed (i.e. all were falsy), return the last operand.

A value is returned in its original form, without the conversion.

In other words, a chain of OR "||" returns the first truthy value or the last one if no such value is found.

For instance:

alert( 1 || 0 ); // 1 (1 is truthy)
alert( true || 'no matter what' ); // (true is truthy)

alert( null || 1 ); // 1 (1 is the first truthy value)
alert( null || 0 || 1 ); // 1 (the first truthy value)
alert( undefined || null || 0 ); // 0 (all falsy, returns the last value)