Falsy Bouncer

easy
By FrontendAtlas Editorial · Updated Oct 10, 2026
Remove all falsy values from an array while preserving order. Use a boolean filter to drop false, 0, empty string, null, undefined, and NaN without mutating the input. Concepts: arrays, filtering, truthy-falsy, functional.

Arguments

  • arr: any[] — An array containing any types of elements, including falsy values.

Returns

any[] — A new array with all falsy values removed.

Solution idea

Use the Boolean constructor as a predicate to filter out falsy values. This keeps only truthy entries, preserves order, and avoids manual checks for null, undefined, or empty strings. It’s a concise, idiomatic solution that’s easy to read and easy to explain in interviews. Key concepts: arrays, filtering, truthy-falsy.

Examples
// Basic examples
compact([0, 1, false, 2, '', 3]) // => [1, 2, 3]

// Works with only truthy values
compact(['a', true, 42]) // => ['a', true, 42]

// Handles null and undefined
compact([null, undefined, 'x']) // => ['x']

// Handles NaN
compact([NaN, 1, 2]) // => [1, 2]