Programming Useful

Use Array.filter() to Remove Falsy Values

Removing null, undefined, 0, false, NaN from arrays requires complex conditional logic. Use Array.filter(Boolean) to remove all falsy values in one line.

Problem

Removing null, undefined, 0, false, NaN from arrays requires complex conditional logic.

Solution

Use Array.filter(Boolean) to remove all falsy values in one line.

Benefit

Eliminates 10+ lines of conditional logic and handles all falsy values automatically.

Code Example

const arr = [0, 1, false, 2, '', 3, null, undefined, NaN];

// Remove all falsy values
const clean = arr.filter(Boolean);
// Result: [1, 2, 3]

ES
Edrees Salih
6 hours ago

We are still cooking the magic in the way!