[ Web Proxy ]
URL:
Viewing: https://www.javascripttutorial.net/javascript-tutorial/javascript-falsy/ [Back]  [Original]

JavaScript Falsy
Skip to content

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);Code language: JavaScript (javascript)

Output:

trueCode 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:

trueCode 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:

falseCode language: JavaScript (javascript)

 

Was this tutorial helpful ?
Yes No
Search …:

Getting Started

JavaScript Fundamentals

JavaScript Operators

Control Flow

JavaScript Functions

JavaScript Objects

Classes

Advanced Functions

Promises & Async/Await

JavaScript Modules

Javascript Error Handling

JavaScript Runtime

Primitive Wrapper Types

More JavaScript Operators

Copyright © 2009 - Present by JavaScript Tutorial Website. All Right Reserved.


Web Proxy Viewer  |  New URL  |  Original Page