Logical Operators in JavaScript

The logical operators && and || have special “short-circuiting” behavior and sometimes only evaluate one of their arguments. Common JavaScript idioms require you to understand the special behavior of these operators.

The logical AND (&&) and OR (||) operators in JavaScript do indeed exhibit “short-circuiting” behavior. This means that they only evaluate as much as necessary to determine the outcome, then they stop, or “short-circuit”.

  1. Logical AND (&&):

In the && operation, if the first operand is falsy (i.e., evaluates to false), JavaScript immediately knows that the result cannot be true, regardless of the value of the second operand. So it short-circuits, returns the first operand and doesn’t even evaluate the second operand. If the first operand is truthy (i.e., evaluates to true), JavaScript needs to check the second operand to determine the final result. Therefore, it evaluates and returns the second operand.

Here’s a code example:

1
2
3
console.log(false && anything); // outputs: false
console.log(true && 'hello'); // outputs: 'hello'
console.log(true && false); // outputs: false

In the first line, anything can be any expression, but it’s never evaluated because false && anything is always false.

  1. Logical OR (||):

In the || operation, if the first operand is truthy, JavaScript immediately knows that the result will be true, regardless of the value of the second operand. So it short-circuits, returns the first operand and doesn’t evaluate the second operand. If the first operand is falsy, JavaScript needs to check the second operand to determine the final result. Therefore, it evaluates and returns the second operand.

Here’s a code example:

1
2
3
console.log(true || anything); // outputs: true
console.log(false || 'hello'); // outputs: 'hello'
console.log(false || false); // outputs: false

In the first line, anything can be any expression, but it’s never evaluated because true || anything is always true.

These characteristics of && and || can be exploited in useful ways in JavaScript. For example, they can be used to provide default values for function arguments:

1
2
3
4
5
6
7
function greet(name) {
  name = name || "Guest";
  console.log("Hello, " + name + "!");
}

greet("Alice");  // Outputs: "Hello, Alice!"
greet();         // Outputs: "Hello, Guest!"

In this case, if no argument is passed to the greet function, name is undefined, which is falsy. So the || operator evaluates and returns “Guest” as the default value.