How Lodash _.without Filters Undefined Arrays
This article examines how the Lodash utility function
_.without operates when applied to an array strictly
populated with undefined values. It explores the internal
mechanics of Lodash's difference algorithms, how undefined
is treated during equality comparisons, and what results developers
should expect across various filtering scenarios.
The
Underlying Mechanism: baseDifference and SameValueZero
At its core, _.without creates an array excluding all
provided values. Internally, Lodash delegates _.without to
baseDifference. This internal function iterates over the
target array and compares each element against the exclusion values.
The comparison relies on the SameValueZero
algorithm. SameValueZero operates similarly to strict equality
(===), with the exception that it considers
NaN equal to NaN. When dealing with
undefined, SameValueZero evaluates
undefined === undefined as true.
Filtering Out
undefined Values
If you pass undefined as an argument to exclude from an
array containing only undefined elements, Lodash recognizes
every item as a match.
const array = [undefined, undefined, undefined];
const result = _.without(array, undefined);
// result => []During execution:
_.withoutgathers the values to exclude into an array:[undefined].- Lodash inspects each element of the input array.
- Every element matches the exclusion criteria via SameValueZero comparison.
- The matching elements are omitted, returning a new, empty array
(
[]).
Filtering With Other Criteria
If _.without is called on the array without specifying
undefined as a target value, no elements match the
exclusion criteria.
const array = [undefined, undefined];
// Excluding a different primitive
const resultWithNull = _.without(array, null);
// resultWithNull => [undefined, undefined]
// Invoking without exclusion arguments
const resultNoArgs = _.without(array);
// resultNoArgs => [undefined, undefined]Because undefined does not equal null,
false, 0, or any other value under
SameValueZero, none of the elements are stripped. Lodash returns a new
shallow-copied array containing the original undefined
elements.
Internal Optimization and Cache Handling
When a large number of exclusion values are passed to
_.without, Lodash optimizes lookups by generating an
internal SetCache (wrapping JavaScript's native
Set). Native JavaScript sets accurately store and retrieve
undefined. Therefore, whether the exclusion list is small
(using linear scanning via arrayIncludes) or large (using
SetCache), the matching logic for undefined
remains constant, reliable, and performs in expected time complexities
without edge-case failures.