Logical Operators
Javascript has the following logical operators:
&&
and||
or!
not
The logical operators work as expected when their operands are boolean expressions. For instance, x && y
will return true if both x
and y
evaluate to true. The operator will also employ short-circuiting; it will not evaluate y
if x
evaluates to false.
const isCitizen = true; const age = 28; console.log(isCitizen && age > 64);
Let's revisit the earlier statement:
The logical operators work normally when their operands are boolean expressions.
What if their operands are not boolean expressions? Hmm, you may be thinking the operands are probably converted to boolean and then ... let me stop you right there. Embrace yourself for madness!
The JavaScript &&
and ||
operators don't return a boolean!! They always return one of their operands! If the operands happened to be booleans, then it looks like everything works as expected. But things get weird when one or more operands are not boolean!
Here is what really happens:
x && y
: Ifx
can be converted to true, returnsy
; else, returnsx
.
console.log(true && "Ali"); console.log(false && "Ali");
x || y
: Ifx
can be converted to true, returnsx
; else, returnsy
.
console.log(true || "Ali"); console.log(false || "Ali");
The JavaScript community has (perhaps, unfortunately) embraced these features. You will find expressions such as
DEBUG && console.log("Some debugging message");
which is a short form of
if (DEBUG) {
console.log("Some debugging message");
}
The variable DEBUG
is presumably a boolean value, but it does not have to be. (See the next section!)
Resources
- For a more in-depth consideration of logical operators, read Aashni's "Lazy Evaluations and Short Circuit Logic in Javascript."