How to Check if a Value is Falsy in JavaScript

avatar

Borislav Hadzhiev

Mon Oct 18 20212 min read

Check if a Value is Falsy in JavaScript #

Use the logical NOT (!) operator to check if a value is falsy, e.g. if (!myValue). The logical NOT operator returns true when it precedes falsy values, in all other cases it returns false.

index.js
const myVar = 0; if (!myVar) { console.log('โœ… myVar is falsy'); } else { console.log('โ›”๏ธ myVar is truthy'); }

We use the logical NOT (!) operator to check if the myVar variable stores a falsy value.

The falsy values in JavaScript are: false, 0, -0, empty string, null, undefined, NaN.

Our if block would run only if the value stored in the myVar variable is one of these values.

Here are examples of using the logical NOT (!) operator with falsy values:

index.js
console.log(!false); // ๐Ÿ‘‰๏ธ true console.log(!0); // ๐Ÿ‘‰๏ธ true console.log(!''); // ๐Ÿ‘‰๏ธ true console.log(!null); // ๐Ÿ‘‰๏ธ true console.log(!undefined); // ๐Ÿ‘‰๏ธ true console.log(!NaN); // ๐Ÿ‘‰๏ธ true

All other values are considered truthy.

The empty array and empty object are considered two of the more confusing truthy values. Here are examples:
index.js
if (![]) { console.log("โ›”๏ธ This doesn't run"); } else { console.log('โœ… This runs'); } if (!{}) { console.log("โ›”๏ธ This doesn't run"); } else { console.log('โœ… This runs'); }

Even though the array and object are empty, they are not one of the falsy values, as opposed to the empty string.

index.js
if (!"") { console.log('โœ… This runs'); } else { console.log("โ›”๏ธ This doesn't run"); }

If you need to check if an array or object contains elements or key-value pairs, do this instead:

index.js
if (['a'].length > 0) { // ๐Ÿ‘‰๏ธ array is not empty } if (Object.keys({a: 'b'}).length > 0) { // ๐Ÿ‘‰๏ธ object is not empty }

In the example, we basically check if the array contains at least 1 element and the object at least 1 key-value pair.

You could also do the check implicitly, e.g.:

index.js
if ([].length) { // ๐Ÿ‘‰๏ธ if this runs, the array is not empty }

In this example, we access the length property on an empty array, which evaluates to 0. Because 0 is a falsy value, the if block doesn't run.

Further Reading #

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee