Lodash _.reduce on Plain Object Without Accumulator

When you execute Lodash's _.reduce method on a plain JavaScript object without passing an initial accumulator value, Lodash automatically assigns the value of the object's first enumerable property as the initial accumulator. It then begins iterating through the remaining properties starting from the second entry, passing the running accumulator, the current property value, the current key, and the original object into your callback function. If the provided object is empty, the function immediately returns undefined.

The Core Mechanism

Lodash normalizes collections across arrays and objects. When accumulator is omitted from _.reduce(collection, iteratee, [accumulator]), the method defaults to extracting the first element:

  1. Initial Accumulator Assignment: Lodash resolves the object's own enumerable string keys. The value corresponding to the first resolved key is set as the accumulator.
  2. Iteration Offset: The first key-value pair is skipped in the iteration loop because its value is already assigned as the base accumulator.
  3. Iteratee Invocation: For every subsequent property, the iteratee callback is invoked with four arguments: (accumulator, value, key, collection).
  4. Final Return Value: Once all remaining properties are processed, the final resolved accumulator is returned.

Code Example

const _ = require('lodash');

const scores = {
  math: 85,
  science: 90,
  history: 75
};

const total = _.reduce(scores, (acc, value, key) => {
  return acc + value;
});

console.log(total); // Output: 250

In this execution:

Handling Empty Objects

If the plain object contains no own enumerable properties, Lodash cannot extract an initial value.

const emptyObj = {};

const result = _.reduce(emptyObj, (acc, value) => {
  return acc + value;
});

console.log(result); // Output: undefined

Because the iteratee is never called on an empty collection without an initial accumulator, _.reduce evaluates to undefined.

Important Considerations and Edge Cases