How to Remove Falsy Values from Array in JavaScript
Array.prototype.filter() method with the Boolean constructor as the callback. This filters out all values that are false, 0, '', null, undefined, or NaN, leaving only truthy values.Syntax
The syntax to remove falsy values uses the filter() method with Boolean as the callback function.
array.filter(Boolean)
Here, filter() goes through each item in the array and keeps only those where Boolean(item) is true.
const filteredArray = array.filter(Boolean);
Example
This example shows how to remove all falsy values from an array using filter(Boolean). The original array has false, 0, empty string, null, undefined, and NaN, which are all removed.
const mixedArray = [0, 1, false, 2, '', 3, null, undefined, NaN, 4]; const truthyArray = mixedArray.filter(Boolean); console.log(truthyArray);
Common Pitfalls
A common mistake is trying to filter falsy values with a callback that returns the item directly, which can cause unexpected results if the item is falsy but you want to keep it. Also, using filter(item => item !== false) only removes false but keeps other falsy values like 0 or ''.
Using filter(Boolean) is the simplest and most reliable way to remove all falsy values.
const arr = [0, false, '', null, undefined, NaN, 1]; // Wrong: only removes false, keeps other falsy values const wrongFilter = arr.filter(item => item !== false); console.log(wrongFilter); // Output: [0, '', null, undefined, NaN, 1] // Right: removes all falsy values const rightFilter = arr.filter(Boolean); console.log(rightFilter); // Output: [1]
Quick Reference
Summary tips for removing falsy values from arrays:
- Use
array.filter(Boolean)to remove all falsy values. - Falsy values include:
false,0,''(empty string),null,undefined, andNaN. - Do not use custom filters unless you want to keep some falsy values.