The primitive boolean type comprises the values true
and false
:
> typeof false 'boolean' > typeof true 'boolean'
Values are converted to booleans as follows:
Value | Converted to boolean |
|
|
|
|
A boolean | Same as input (nothing to convert) |
A number |
|
other numbers → | |
A string |
|
other strings → | |
An object |
|
There are three ways any value can be converted to a boolean:
| (Invoked as a function, not as a constructor) |
| |
| A single “not” converts to negated boolean; use twice for the nonnegated conversion. |
I prefer Boolean()
, because it is more descriptive. Here are some examples:
> Boolean(undefined) false > Boolean(null) false > Boolean(0) false > Boolean(1) true > Boolean(2) true > Boolean('') false > Boolean('abc') true > Boolean('false') true
Wherever JavaScript expects a boolean, you can provide any kind of value and it is automatically converted to boolean. Thus, there are two sets of values in JavaScript: one set is converted to false
, while the other set is converted to true
. These sets are called falsy values and truthy values. Given the preceding table, the following are all falsy values:
undefined
, null
false
0
, NaN
''
All other values—including all objects, even empty objects, empty arrays, and new Boolean(false)
—are truthy. Because undefined
and null
are falsy, you can use the if
statement to check whether a variable x
has a value:
if
(
x
)
{
// x has a value
}
The caveat is that the preceding check interprets all falsy values as “does not have a value,” not just undefined
and null
. But if you can live with that limitation, you get to use a compact and established pattern.
All objects are truthy:
> Boolean(new Boolean(false)) true > Boolean([]) true > Boolean({}) true
That is different from how objects are converted to a number or string, where you can control the result by implementing the methods valueOf()
and toString()
:
> Number({ valueOf: function () { return 123 } }) 123 > String({ toString: function () { return 'abc' } }) 'abc'
The conversion to boolean is different for historic reasons. For ECMAScript 1, it was decided to not enable objects to configure that conversion (e.g., via a toBoolean()
method). The rationale was that the boolean operators ||
and &&
preserve the values of their operands. Therefore, if you chain those operators, the same value may be checked multiple times for truthiness or falsiness. Such checks are cheap for primitives, but would be costly for objects if they were able to configure their conversion to boolean. ECMAScript 1 avoided that cost by making objects always truthy.
In this section, we cover the basics of the And (&&), Or (||), and Not (!) logical operators.
Binary logical operators are:
They always return either one of the operands, unchanged:
> 'abc' || 123 'abc' > false || 123 123
The second operand is not evaluated if the first operand already determines the result. For example (the result of console.log
is undefined
):
> true || console.log('Hello') true > false || console.log('Hello') Hello undefined
That is uncommon behavior for operators. Normally, all operands are evaluated before an operator is invoked (just like for functions).
If the first operand can be converted to false
, return it. Otherwise, return the second operand:
> true && false false > false && 'def' false > '' && 'def' '' > 'abc' && 'def' 'def'
If the first operand can be converted to true
, return it. Otherwise, return the second operand:
> true || false true > true || 'def' true > 'abc' || 'def' 'abc' > '' || 'def' 'def'
theValue
||
defaultValue
The parameter text
of the function saveText()
is optional and should be the empty string if it has been omitted:
function
saveText
(
text
)
{
text
=
text
||
''
;
...
}
This is the most common use of ||
as a default operator. Consult Optional Parameters for more on optional parameters.
The object options
may or may not have the property title
. If it is missing, the value 'Untitled'
should be used when setting the title:
setTitle
(
options
.
title
||
'Untitled'
);
The function countOccurrences
counts how often regex
matches inside str
:
function
countOccurrences
(
regex
,
str
)
{
// Omitted: check that /g is set for `regex`
return
(
str
.
match
(
regex
)
||
[]).
length
;
}
The problem is that match()
(see String.prototype.match: Capture Groups or Return All Matching Substrings) either returns an array or null
. Thanks to ||
, a default value is used in the latter case. Therefore, you can safely access the property length
in both cases.
The logical not operator !
converts its operand to boolean and then negates it:
> !true false > !43 false > !'' true > !{} false
The following operators are covered elsewhere:
===
, !==
, ==
, !=
(see Equality Operators: === Versus ==)
>
, >=
, <
, <=
(see Ordering Operators)
The function Boolean
can be invoked in two ways:
Boolean(value)
As a normal function, it converts value
to a primitive boolean (see Converting to Boolean):
> Boolean(0) false > typeof Boolean(false) // no change 'boolean'
new Boolean(bool)
As a constructor, it creates a new instance of Boolean
(see Wrapper Objects for Primitives), an object that wraps bool
(after converting it to a boolean). For example:
> typeof new Boolean(false) 'object'
The former invocation is the common one.