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:
false: The boolean literal representing falsehood.null: The primitive value representing the intentional absence of any object value.0: The number zero (including-0and0n/BigInt(0))."": An empty string (strings with a length of zero, defined by"",'', or\``\).undefined: The primitive value automatically assigned to variables that have just been declared or arguments that have not been supplied.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:
- Empty objects (
{}): Objects are truthy, even when they contain no keys. - Empty arrays (
[]): Arrays are objects in JavaScript and evaluate totrue. - Whitespace strings (
" "): Any string with at least one character—including a space, tab, or newline—is truthy. - The string
"0"or"false": Non-empty strings evaluate totrue, regardless of the text they contain.