0
0
JavascriptHow-ToBeginner · 3 min read

How to Remove Falsy Values from Array in JavaScript

To remove falsy values from an array in JavaScript, use the 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.

javascript
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.

javascript
const mixedArray = [0, 1, false, 2, '', 3, null, undefined, NaN, 4];
const truthyArray = mixedArray.filter(Boolean);
console.log(truthyArray);
Output
[1, 2, 3, 4]
⚠️

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.

javascript
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]
Output
[0, "", null, undefined, NaN, 1] [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, and NaN.
  • Do not use custom filters unless you want to keep some falsy values.

Key Takeaways

Use array.filter(Boolean) to remove all falsy values from an array.
Falsy values are false, 0, '', null, undefined, and NaN.
Avoid custom filters that only remove some falsy values unless intentional.
filter(Boolean) is concise, readable, and reliable for this task.