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:

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');

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:

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: