Javascript has the following logical operators:
&&
and||
or!
notThe 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.
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
: If x
can be converted to true, returns y
; else, returns x
.
x || y
: If x
can be converted to true, returns x
; else, returns y
.
The JavaScript community has (perhaps, unfortunately) embraced these features. You will find expressions such as
which is a short form of
The variable DEBUG
is presumably a boolean value, but it does not have to be. (See the next section!)
For a more in-depth consideration of logical operators, read Aashni’s “Lazy Evaluations and Short Circuit Logic in Javascript.”