How Lodash transform Deduces Accumulator Types

The _.transform method in the Lodash JavaScript library provides an alternative to _.reduce, allowing developers to iterate over collections and mutate an accumulator directly. When the accumulator parameter is omitted, Lodash does not default to undefined or a generic plain object across all cases. Instead, it inspects the input collection’s type, constructor, and prototype chain to construct an appropriate initial accumulator automatically.

1. Array and Array-Like Checks

The first step in the deduction process is determining whether the target collection is an array or an array-like structure (such as a Node.js Buffer or a TypedArray).

2. Objects and Custom Prototypes

If the input is not array-like but qualifies as an object (typeof object === 'object' and not null), Lodash attempts to preserve the prototype hierarchy of the source data:

3. Fallback for Primitives and Edge Cases

If the target object argument is neither array-like nor a valid non-null object (for example, if a primitive value or null is passed), Lodash defaults to a fallback value:

Summary of Deduction Behavior

By analyzing the collection before invocation, Lodash maps inputs to default accumulators as follows:

This automatic deduction allows _.transform to return a data structure that structurally mirrors the source collection without requiring manual initialization.