JavaScript JavaScript Basics

How to Identify Falsy Values in JavaScript

Spread the love

The following values are falsy in JavaScript, which means that if they are casted to a boolean value, it will be false.

  • false
  • 0
  • empty string: "" , '' , or ``
  • null
  • undefined
  • NaN — not a number value

If you evaluate them as boolean like so, you get:

Boolean(false); // false
Boolean(0); // false
Boolean(""); // false
Boolean(''); // false
Boolean(``); // false
Boolean(undefined); // false
Boolean(null); // false
Boolean(NaN); // false

as opposed to truthy values like objects, which are anything else but the values above:

Boolean({}) // true
Boolean(true) // true
Boolean([]) // true

You can also use the !! shortcut to cast to Boolean, the right ! cast the variable into a boolean and negate the value, and the left ! negate it back to the actual boolean value.

!!(false); // false
!!(0); // false
!!(""); // false
!!(''); // false
!!(``); // false
!!(undefined); // false
!!(null); // false
!!(NaN); // false

Similarly for truthy values:

!!({}) // true
!!(true) // true
!!(\[\]) // true

With shortcut evaluation, boolean ANDs and ORs are evaluated up to the first truthy value:

const abc = false && "abc"; // false, since false is false and "abc" is true

const def = false || "def"; // true, since false is false and "def" is true

It is always good to check for falsy values like null and undefined to avoid crashes.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *