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
// ⇒ [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]]

There is more to learn

Get free previews of my upcoming course materials and other bonus content to help you work smarter. I share tips straight to your inbox once a week. You can read previous mails in the newsletter archive.

Cannot show form because cookie consent was not given.