Boolean Values
A boolean value represents truth or falsehood, on or off, yes or
no. There are only two possible values of this type. The reserved
words true and false evaluate to these two values.
Boolean values are generally the result of comparisons you make in your JavaScript programs. For example:
a==4
This code tests to see whether the value of the variable
a is equal to the number 4. If it is, the result of this comparison
is the boolean value true. If
a is not equal to 4, the result of the comparison is false.
Boolean values are commonly used in JavaScript control
structures. For example, the if/else statement in JavaScript performs one
action if a boolean value is true
and another action if the value is false. You usually combine a comparison that
creates a boolean value directly with a statement that uses it. The
result looks like this:
if(a==4)b=b+1;elsea=a+1;
This code checks whether a
equals 4. If so, it adds 1 to b;
otherwise, it adds 1 to a.
As we’ll discuss in Type Conversions, any
JavaScript value can be converted to a boolean value. The following
values convert to, and therefore work like, false:
undefinednull0-0NaN""// the empty string
All other values, including all objects (and arrays) convert to,
and work like, true. false, and the six values that convert to
it, are sometimes called falsy values, and all
other values are called truthy. Any time
JavaScript expects a boolean value, a falsy value works like false and a truthy value works like true ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access