? :
)x && y
), Or (x || y
)
x && y
)||
)||
)!
)The primitive type boolean comprises two values – false
and true
:
These are three ways in which you can convert an arbitrary value x
to a boolean.
Boolean(x)
Most descriptive; recommended.
x ? true : false
Uses the conditional operator (explained later in this chapter).
!!x
Uses the logical Not operator (!
). This operator coerces its operand to boolean. It is applied a second time to get a non-negated result.
Tbl. 4 describes how various values are converted to boolean.
x |
Boolean(x) |
---|---|
undefined |
false |
null |
false |
boolean value | x (no change) |
number value | 0 → false , NaN → false |
other numbers → true |
|
string value | '' → false |
other strings → true |
|
object value | always true |
In JavaScript, if you read something that doesn’t exist (e.g. a missing parameter or a missing property), you usually get undefined
as a result. In these cases, an existence check amounts to comparing a value with undefined
. For example, the following code checks if object obj
has the property .prop
:
To simplify this check, we can use the fact that the if
statement always converts its conditional value to boolean:
Therefore, we can use the following code to check if obj.prop
exists. That is less precise than comparing with undefined
, but also shorter:
This simplified check is so popular that the following two names were introduced:
true
when converted to boolean.false
when converted to boolean.Consulting tbl. 4, we can make an exhaustive list of falsy values:
undefined
, null
false
0
, NaN
''
All other values (incl. all objects) are truthy:
Truthiness checks have one pitfall: they are not very precise. Consider this previous example:
The body of the if
statement is skipped if:
obj.prop
is missing (in which case, JavaScript returns undefined
).However, it is also skipped if:
obj.prop
is undefined
.obj.prop
is any other falsy value (null
, 0
, ''
, etc.).In practice, this rarely causes problems, but you have to be aware of this pitfall.
if (x) {
// x is truthy
}
if (!x) {
// x is falsy
}
if (x) {
// x is truthy
} else {
// x is falsy
}
const result = x ? 'truthy' : 'falsy';
The conditional operator that is used in the last line, is explained later in this chapter.
A truthiness check is often used to determine if the caller of a function provided a parameter:
On the plus side, this pattern is established and short. It correctly throws errors for undefined
and null
.
On the minus side, there is the previously mentioned pitfall: the code also throws errors for all other falsy values.
An alternative is to check for undefined
:
Truthiness checks are also often used to determine if a property exists:
function readFile(fileDesc) {
if (!fileDesc.path) {
throw new Error('Missing property: .path');
}
// ···
}
readFile({ path: 'foo.txt' }); // no error
This pattern is also established and has the usual caveat: it not only throws if the property is missing, but also if it exists and has any of the falsy values.
If you truly want to check if the property exists, you have to use the in
operator:
Exercise: Truthiness
exercises/booleans/truthiness_exrc.mjs
? :
)The conditional operator is the expression version of the if
statement. Its syntax is:
«condition» ? «thenExpression» : «elseExpression»
It is evaluated as follows:
condition
is truthy, evaluate and return thenExpression
.elseExpression
.The conditional operator is also called ternary operator, because it has three operands.
Examples:
The following code demonstrates that, whichever of the two branches “then” and “else” is chosen via the condition – only that branch is evaluated. The other branch isn’t.
x && y
), Or (x || y
)The operators &&
and ||
are value-preserving and short-circuiting. What does that mean?
Value-preservation means that operands are interpreted as booleans, but returned unchanged:
Short-circuiting means: If the first operand already determines the result, then the second operand is not evaluated. The only other operator that delays evaluating its operands is the conditional operator: Usually, all operands are evaluated before performing an operation.
For example, logical And (&&
) does not evaluate its second operand if the first one is falsy:
If the first operand is truthy, console.log()
is executed:
x && y
)The expression a && b
(“a
And b
”) is evaluated as follows:
a
.b
and return the result.In other words, the following two expressions are roughly equivalent:
Examples:
> false && true
false
> false && 'abc'
false
> true && false
false
> true && 'abc'
'abc'
> '' && 'abc'
''
||
)The expression a || b
(“a
Or b
”) is evaluated as follows:
a
.b
and return the result.In other words, the following two expressions are roughly equivalent:
Examples:
> true || false
true
> true || 'abc'
true
> false || true
true
> false || 'abc'
'abc'
> 'abc' || 'def'
'abc'
||
)Sometimes you receive a value and only want to use it if it isn’t either null
or undefined
. Otherwise, you’d like to use a default value, as a fallback. You can do that via the ||
operator:
The following code shows a real-world example:
function countMatches(regex, str) {
const matchResult = str.match(regex); // null or Array
return (matchResult || []).length;
}
If there are one or more matches for regex
inside str
then .match()
returns an Array. If there are no matches, it unfortunately returns null
(and not the empty Array). We fix that via the ||
operator.
Exercise: Default values via the Or operator (
||
)
exercises/booleans/default_via_or_exrc.mjs
!
)The expression !x
(“Not x
”) is evaluated as follows:
x
.false
.true
.Examples:
Quiz
See quiz app.