- Explain What a Boolean Expression Is
- Describe Truthy and Falsey Values in JavaScript
Quite commonly in our computer programs, we want to execute code conditionally, i.e., if some condition is true (or false). For example:
- If the user has entered the correct login credentials, then log them into our web app
- If there isn't enough money in the user's account to execute the transfer, then send them an error message
In the following lessons, we will learn about operators we can use to construct those conditional statements. Before we get to that, however, we need to understand boolean expressions and the concepts of truthy-ness and falsey-ness.
We have learned that expressions are code statements that return a value: the
constant expression returns the value of the constant, the assignment
expression returns the value that is assigned, and the variable lookup
expression returns the value of a variable. We have also learned that
JavaScript has a Boolean
data type that has only two values: true
or
false
. As you might expect, therefore, a Boolean expression is an expression
that returns either true
or false
.
All values in Javascript, of any data type (String
, Number
, etc.), are
treated as either truthy or falsey. The following values are falsey:
false
null
undefined
0
NaN
- An empty string (
""
,''
)
Every other value is truthy.
To check whether a value is truthy or falsey, we can pass it to the global
Boolean
object, which converts the value into its boolean equivalent. You may
want to try these out yourself in
replit.
Boolean(false);
// => false
Boolean(null);
// => false
Boolean(undefined);
// => false
Boolean(0);
// => false
Boolean(NaN);
// => false
Boolean("");
// => false
Boolean(true);
// => true
Boolean(42);
// => true
Boolean("Hello, world!");
// => true
Don't worry if this seems a little theoretical at this point. We will learn how this information is used in constructing Boolean expressions in the following lessons.
In this lesson, we've learned what a Boolean expression is. We've also learned
which values in JavaScript are considered truthy and which are considered
falsey. With these understandings, we are now ready to learn how to construct
Boolean expressions that return true
or false
.