JavaScript Falsy

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:

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:

ValueType
nullnull
undefinedundefined
falseboolean
NaN, 0, -0number
0nbigint
""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);

Output:

true

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));

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);

Output:

true

number #

In the following example, the amount is zero, therefore, it is falsy:

let amount = 0;
console.log(Boolean(amount));

Output:

false

 

Was this helpful?