Falsy Values Removed by Lodash Compact

The Lodash _.compact method is a utility function designed to filter an array by removing all falsy elements and returning a clean, compact array. In JavaScript, a value is considered falsy if it evaluates to false when converted into a boolean context. This guide details the specific types of falsy values eliminated by _.compact and illustrates how the method works with clear code examples.

The Six Falsy Values Removed

Lodash's _.compact method evaluates each element in a given array using standard JavaScript boolean coercion. It removes the following six falsy values:

  1. false: The boolean literal representing falsehood.
  2. null: The primitive value representing the intentional absence of any object value.
  3. 0: The number zero (including -0 and 0n / BigInt(0)).
  4. "": An empty string (strings with a length of zero, defined by "", '', or \``\).
  5. undefined: The primitive value automatically assigned to variables that have just been declared or arguments that have not been supplied.
  6. NaN: The special numeric value representing "Not-a-Number."

Practical Example

When you pass an array containing any combination of these values to _.compact, it filters them out completely, preserving only truthy values.

const _ = require('lodash');

const mixedArray = [
  0,
  1,
  false,
  2,
  '',
  3,
  'hello',
  undefined,
  null,
  NaN,
  'world'
];

const cleanedArray = _.compact(mixedArray);

console.log(cleanedArray);
// Output: [1, 2, 3, 'hello', 'world']

Values Not Removed by _.compact

Developers often confuse certain empty or seemingly false structures with standard JavaScript falsy values. The _.compact method will not remove: