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”.
- 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:
|
|
In the first line, anything
can be any expression, but it’s never evaluated because false && anything
is always false
.
- 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:
|
|
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:
|
|
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.