Lodash _.assign vs _.assignIn: Prototype Chains
In the Lodash JavaScript utility library, both _.assign
and _.assignIn are used to copy properties from one or more
source objects onto a target destination object. The fundamental
difference between them lies in how they navigate prototype chains:
_.assign copies only the source object's own enumerable
properties, while _.assignIn copies both own and inherited
enumerable properties found along the prototype chain. This distinction
determines whether properties defined on a parent prototype will be
transferred to your destination object.
Lodash _.assign
The _.assign method strictly copies an object's
own enumerable string keyed properties to the
destination object. It ignores any properties that the source object
inherits from its prototype chain. This behavior is equivalent to the
native ES6 Object.assign() method.
If a property exists on Source.prototype but is not
directly assigned to the source instance itself, _.assign
will omit it entirely.
const parent = { inheritedProp: 'from prototype' };
const child = Object.create(parent);
child.ownProp = 'from child';
const result = _.assign({}, child);
console.log(result.ownProp); // 'from child'
console.log(result.inheritedProp); // undefinedLodash _.assignIn
The _.assignIn method (previously aliased as
_.extend) copies both own and inherited
enumerable properties from the source object to the destination
object.
When _.assignIn executes, it walks up the prototype
chain of the source object, identifies all enumerable properties, and
assigns them as own properties directly onto the destination object.
const parent = { inheritedProp: 'from prototype' };
const child = Object.create(parent);
child.ownProp = 'from child';
const result = _.assignIn({}, child);
console.log(result.ownProp); // 'from child'
console.log(result.inheritedProp); // 'from prototype'
console.log(result.hasOwnProperty('inheritedProp')); // trueDirect Comparison
| Feature | _.assign |
_.assignIn |
|---|---|---|
| Copies Own Properties | Yes | Yes |
| Copies Inherited Properties | No | Yes |
| Traverses Prototype Chain | No | Yes |
| Native Equivalent | Object.assign() |
None (manual for...in
loop) |
| Lodash Alias | None | _.extend |
When to Use Which
Use _.assign for standard object merging, handling plain
JavaScript objects (POJOs), and preventing unexpected inherited
properties from polluting your destination object.
Use _.assignIn when working with custom class instances,
prototype-based inheritance models, or when you explicitly need to
flatten an inheritance structure into a single plain object containing
all accessible properties.