Before we discuss the operators themselves, we need to acquaint ourselves with
JavaScript’s mechanism for mapping nonboolean values to boolean values.
Truthy and Falsy Values
Many languages have a concept of “truthy” and “falsy” values; C, for example, doesn’t
even have a boolean type: numeric 0 is false, and all other numeric values are true.
JavaScript does something similar, except it includes all data types, effectively allow‐
ing you to partition any value into truthy or falsy buckets. JavaScript considers the
following values to be falsy:
•
undefined
•
null
•
false
•
0
•
NaN
•
''
(an empty string)
Everything else is truthy. Because there are a great number of things that are truthy, I
won’t enumerate them all here, but I will point out some you should be conscious of:
• Any object (including an object whose
valueOf()
method returns
false
)
• Any array (even an empty array)
• Strings containing only whitespace (such as
" "
)
• The string
"false"
Some people stumble over the fact that the string
"false"
is
true
, but for the most
part, these partitions make sense, and are generally easy to remember and work with.
One notable exception might be the fact that an empty array is truthy. If you want an
array
arr
to be falsy if it’s empty, use
arr.length
(which will be 0 if the array is
empty, which is falsy).
AND, OR, and NOT
The three logical operators supported by JavaScript are AND (
&&
), OR (
||
), and NOT
(
!
). If you have a math background, you might know AND as conjunction, OR as dis‐
junction, and NOT as negation.
Unlike numbers, which have infinite possible values, booleans can take on only two
possible values, so these operations are often described with truth tables, which com‐
pletely describe their behavior (see Tables
).
AND, OR, and NOT | 89