Summary: in this tutorial, you will learn about JavaScript falsy values and understand how they behave in different boolean contexts.
In JavaScript, the boolean
type includes two values true
and false
.
When you use a non-boolean value in a place that requires a boolean value, JavaScript will coerce that value to a boolean value.
Coercion means JavaScript automatically converts a value from one type to another implicitly.
The places where JavaScript expects a boolean value are called boolean contexts.
In JavaScript, boolean contexts are in the conditional statements such as:
- if
- while
- do while
- for
- and logical operators NOT, AND, and OR.
A falsy value is a value that evaluates to false
when used in a boolean context. Sometimes, a falsy value is written falsey.
The following table lists all the falsy values in JavaScript:
Value | Type |
---|---|
null | null |
undefined | undefined |
false | boolean |
NaN , 0 , -0 | number |
0n | bigint |
"" | string |
Note that document.all
is the only object in JavaScript that is falsy. But this object was deprecated and will be removed.
Other values that are not falsy are truthy.
JavaScript falsy examples
Let’s take some examples of using falsy values
null
The following example shows true in the console because x
is null
, which evaluates to false
. The not operator (!) turns false
to true
:
let x = null;
console.log(!x);
Code language: JavaScript (javascript)
Output:
true
Code language: JavaScript (javascript)
undefined
The following example returns false
because x
is not initialized therefore it is undefined
. The Boolean
function converts undefined to false
.
let x;
console.log(Boolean(x));
Code language: JavaScript (javascript)
string
The following example displays true because the message
variable holds an empty string (''
), which is a falsy value. The not (!
) operator negates the falsy to truthy:
let message = '';
console.log(!message);
Code language: JavaScript (javascript)
Output:
true
Code language: JavaScript (javascript)
number
In the following example, the amount is zero, therefore, it is falsy:
let amount = 0;
console.log(Boolean(amount));
Code language: JavaScript (javascript)
Output:
false
Code language: JavaScript (javascript)