Lodash meanBy Handling of Undefined Values
This article examines how the Lodash JavaScript library handles
strictly undefined object properties when calculating
averages using _.meanBy. It details the internal summation
and division logic, explains why runtime exceptions are prevented, and
explores the resulting output when single, multiple, or all properties
in a collection resolve to undefined.
Silent Fallback and Error Suppression
Lodash adheres to a defensive programming philosophy across its
utility suite. When _.meanBy iterates over an array of
objects and attempts to access an object property that is strictly
undefined (or entirely undeclared), it does not throw a
TypeError or any other runtime exception. Instead, Lodash
safely accesses the property using internal iteratee handlers and
processes the undefined value through standard execution
paths.
The Internal baseSum
Logic
The computation performed by _.meanBy relies internally
on baseMean, which delegates to baseSum.
During the iteration loop in baseSum, each element is
transformed by the iteratee function, and an explicit equality check is
performed:
if (current !== undefined) {
result = result === undefined ? current : (result + current);
}Because of this conditional check:
- Skipped Addition: Any item whose iteratee evaluates
to
undefinedis ignored during summation. It is not added to the running total. - No String or NaN Coercion During Addition: In
standard JavaScript, adding a number to
undefinedproducesNaN. Lodash avoids this by simply bypassing any index that yieldsundefined.
Denominator Calculation and Average Discrepancies
While undefined values are excluded from the numerator
(the sum), Lodash does not exclude them from the
denominator (the divisor).
baseMean calculates the average by dividing the result
of baseSum by the total length of the original collection
(array.length), not the count of defined entries:
return length ? (baseSum(array, iteratee) / length) : NAN;For example, if you evaluate:
const items = [{ val: 10 }, { val: undefined }];
_.meanBy(items, 'val');baseSumcalculates10(skipping the second element).- The array length is
2. - The return value is
5(10 / 2), rather than10.
Behavior When All Properties Are Undefined
If every element in the collection evaluates to
undefined, baseSum completes its loop without
updating its internal accumulator. As a result, baseSum
returns undefined.
When baseMean attempts to compute the average:
- The mathematical operation becomes
undefined / length. - In JavaScript arithmetic, dividing
undefinedby any number evaluates toNaN.
Consequently, when all iterated properties are strictly
undefined, _.meanBy returns
NaN.
Difference Between
undefined, null, and NaN
Understanding Lodash's error handling requires noting how
undefined is distinguished from other falsy or non-numeric
values:
undefined: Filtered out by thecurrent !== undefinedcondition inbaseSum.null: Not filtered out. JavaScript coercesnullto0during arithmetic addition (result + null), contributing0to the total sum.NaN: Not filtered out. AddingNaNto any number results inNaN, which poisons the accumulator and forces the final output of_.meanByto beNaN.