Lodash compact on Uninitialized Array Slots
When Lodash's _.compact method is executed on an array
containing uninitialized slots—commonly known as a sparse array—it
strips out those empty slots entirely. Because JavaScript evaluates
uninitialized slots as undefined when accessed during
iteration, and undefined is a falsey value,
_.compact filters them out along with standard falsey
elements, returning a dense array containing only the remaining truthy
values.
How Lodash Handles Sparse Arrays
An uninitialized slot occurs when an array is initialized with empty
slots (such as new Array(3)) or when an element is skipped
using array literal syntax (such as [1, , 3]). These slots
are not set to undefined; rather, the indices simply do not
exist on the array object.
However, _.compact iterates over the target array using
a standard index-based loop or iterator. When indexed access occurs on a
missing slot (e.g., array[1]), JavaScript returns
undefined.
Lodash treats the following values as falsey:
falsenull0""(empty string)undefinedNaN
Because the uninitialized slot resolves to undefined, it
fails Lodash's truthiness check (if (value)) and is
excluded from the returned array.
Code Example
const _ = require('lodash');
// Create an array with an uninitialized slot
const sparseArray = [1, , 3];
console.log(sparseArray.length); // 3
console.log(1 in sparseArray); // false (index 1 is uninitialized)
// Run _.compact
const compactedArray = _.compact(sparseArray);
console.log(compactedArray); // [1, 3]
console.log(compactedArray.length); // 2
console.log(1 in compactedArray); // true (index 1 now holds the value 3)Key Differences from Native Array Methods
Unlike native methods such as Array.prototype.forEach or
Array.prototype.map, which automatically skip uninitialized
slots without evaluating them, _.compact effectively
normalizes them. The resulting array is guaranteed to be a dense array
without gaps, containing only truthy elements and with an updated
length property that reflects only the retained items.