This post will discuss how to remove all falsy values from an array in JavaScript. The solution should return a new array that excludes all falsy values.

There are 7 falsy values in JavaScript – false, zero (0), BigInt (0n), empty string ("", '', ``), null, undefined, and NaN. An array in JavaScript permits all types of falsy values. There are several methods to filter falsy values from an array, which are covered below:

1. Boolean constructor

The recommended solution is to pass the Boolean constructor to the filter() method to filter out all the’ falsy’ values from the array. This works since the Boolean constructor returns false on any falsy value and vice versa.

Download  Run Code

2. Using !!x Expression

Alternatively, you can use the !!x expression, which returns false on any falsy value. This is demonstrated below:

Download  Run Code

3. Using x => x

Here’s another simple way to filter a falsy value from an array:

Download  Run Code

 
Sometimes you want to retain the value 0 and remove all other falsy values present in the array. You can achieve this as:

Download  Run Code

4. Using Underscore/Lodash Library

Similar to the Array.prototype.filter() method, Underscore and Lodash Library provide their implementation of the filter() method. You can pass any of the above callback functions to the _.filter method and get the same result.

Download Code

5. Using jQuery

In jQuery, you can use the $.grep() method, which removes items from an array that fails the specified condition. The following example demonstrates.

Download Code

That’s all about removing all empty values from an array in JavaScript.