Filtering falsy values from arrays

The constructor for Boolean values is all you need to filter all falsy values from an array. Keep in mind that this takes out false, 0, null, undefined, empty strings, and NaN. If you don’t want that, filter by something more specific.

const values = [
  5, null, false, 'hi', 0, undefined, { name: 'Tim' }, '', true, NaN, [7]
]

// `Boolean` takes out ALL falsy values
values.filter(Boolean)
// ⇒ [5, 'hi', { name: 'Tim' }, true, [7]]

// `x != null` leaves most falsy values, taking out `null` and `undefined`
values.filter(value => value != null)
// ⇒ [5, false, 'hi', 0, { name: 'Tim' }, '', true, NaN, [7]]

More fire tips

Read all fire tips →