What are Falsy Values in JavaScript?

What are Falsy Values in JavaScript?

Introduction

All values in JavaScript have an inherent boolean value.

This means they can either check true truthy values or false falsy values. It is useful to know this, especially when working with conditionals and comparisons.

JavaScript has only six falsy values. All others are truthy values.

You can memorize them. That way, when you come across any value that isn't one of the six, you know it's a truthy value.

List Of All Falsy Values in JavaScript

The following is a list of the six falsy values in JavaScript.

// Falsy Values in JavaScript

false
0
"" or '' or `` (empty string)
NaN
null
undefined

Everything else is a truthy value including all the values in the list below.

Truthy Values That May Surprise you

The following is a list of some values that may appear falsy but are actually truthy values. When we log the boolean values of these values, they return true.

// a string containing the text "false"
console.log(Boolean("false")) // Prints true

// a string containing zero
console.log(Boolean("0")) // Prints true

// a string containing whitespace character
console.log(Boolean("  ")) // Prints true

// an empty object
console.log(Boolean({})) // Prints true

// an empty array
console.log(Boolean([])) // Prints true

// an empty function
console.log(Boolean(function(){ })) // Prints true

You may find it surprising that some of the values mentioned here are truthy. But, keep in mind, any value not present in the list of falsy values evaluates to true.

How to Check if a Value is Falsy

A safe way to check if a value is falsy is to use the logical NOT operator (!).

The (!) operator will return true when called on a falsy value. Let's see an example.

const myValue = 0

if (!myValue) { console.log("Falsy") } // Prints Falsy

Thanks for reading.

Let's connect on LinkedIn | Twitter