Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

_.extend vs _.clone in lodash

To inherit properties of one object by another while dealing with JavaScript objects, I often see usage of _.clone where the intention was to create an object with another object's properties and then it would be extended.

Why can't we just use _.extend which is more relevant to extend an object?

Please tell me the difference between the two and why we can't _.extend instead of _.clone which is a costly operation.

like image 659
Madav Avatar asked Dec 09 '16 15:12

Madav


People also ask

What does Lodash extend do?

extend lodash method works by assigning the own properties, and prototype properties of one or more objects to an object. Assigning is another term for referencing, rather than copying, or cloning.

What is clone in Lodash?

Sep 20, 2019. Lodash's clone() function is a powerful utility for shallow cloning generic objects. The Object. assign() function or the spread operator are the canonical methods for shallow copying a POJO.

How do I clone an array using Lodash?

In order to deep copy an array using Lodash, you can use the _. cloneDeep() method. Note: The _. cloneDeep() method functions by creating a fully independent yet exact copy of supplied values.

What is the most efficient way to deep clone an object in JavaScript?

assign() was the most popular way to deep copy an object. Object. assign() will copy everything into the new object, including any functions. Mutating the copied object also doesn't affect the original object.


2 Answers

_.extend mutates the object. _.clone creates a copy by values, not by reference and does not change the original object. Please note that _.extend is merely an alias for _.assignIn.

_.assignIn(object, [sources])

Note: This method mutates object.

https://lodash.com/docs/4.17.2#assignIn

Also see documenation for _.clone:

https://lodash.com/docs/4.17.2#clone

like image 200
connexo Avatar answered Oct 14 '22 13:10

connexo


If you _.extend() an existing object, you mutate the object. If you _.clone() it first, the original object remains untouched.

You could of course extend an empty object with the original object's properties and some additional ones, which also leaves the original object unchanged:

_.extend({}, originalObject, {
    additionalProperty: "foo"
})

This works very similar to a shallow clone of originalObject. With ES2015, you can achieve the same goal with plain JavaScript and Object.assign().


Additional reading:

  • Why is immutability important in JavaScript?
like image 44
TimoStaudinger Avatar answered Oct 14 '22 12:10

TimoStaudinger