Filtering falsy values from arrays

Posted on July 20, 2020

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]]
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]]

Continue reading

July 5, 2020JavaScript

Logging as objects

This neat little trick makes values logged to the console much more readable with a minor adjustment to how we log it.

Read full article

Read all snippets →