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).
- Standard Arrays: If
Array.isArray(object)evaluates totrue, Lodash uses the collection's constructor (new object.constructor()) to instantiate an empty array. - Array-Like / Typed Collections: If the object is a
Buffer or a TypedArray, Lodash defaults the accumulator to a standard
empty array (
[]) to provide a safe, mutable container for arbitrary values.
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:
- Prototype Inheritance: Lodash inspects the object's
constructor. If the constructor is a function, it creates a new
accumulator using
Object.create(Object.getPrototypeOf(object)). This ensures that the generated accumulator inherits any prototype methods and properties defined on the original object's class or prototype chain. - Plain Objects: For standard object literals
(
{}), this mechanism naturally yields a fresh, empty plain object inheriting fromObject.prototype.
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:
- The method assigns a fresh empty plain object (
{}) as the accumulator.
Summary of Deduction Behavior
By analyzing the collection before invocation, Lodash maps inputs to default accumulators as follows:
[1, 2, 3]\(\rightarrow\)[]{ a: 1, b: 2 }\(\rightarrow\){}new CustomClass()\(\rightarrow\) An empty object inheriting fromCustomClass.prototypenull/ Primitives \(\rightarrow\){}
This automatic deduction allows _.transform to return a
data structure that structurally mirrors the source collection without
requiring manual initialization.