I know that extending objects is done via the
_.extend(parent, child);
method.
I've seen different places in the web where people are extending objects in a special way in underscore.js
_.extend({}, this, child);
Why do they do that?
Lodash and Underscore are great modern JavaScript utility libraries, and they are widely used by Front-end developers.
The _. extend() function is used to create a copy of all of the properties of the source objects over the destination object and return the destination object. The nested arrays or objects will be copied by using reference, not duplicated.
It provides utility functions for a variety of use cases in our day-to-day common programming tasks. Underscore. js provides a lot of features that make our task easy to work with objects. It can be used directly inside a browser and also with Node.
But Sometimes You Do Need Lodash Not every Lodash utility is available in Vanilla JavaScript. You can't deep clone an object, for example. That's why these libraries are far from obsolete. But if you're loading the entire library just to use a couple of methods, that's not the best way to use the library.
According to the underscore documentation, The api of _.extend method is
_.extend(destination, *sources)
First Sample
_.extend(parent, child);
In this sample code, you are actually extending the properties from child object to parent object. Here the parent object is modified.
Second Sample
_.extend({}, parent, child);
In case you don't want to modify the parent object, and still want both the properties from parent and child. You can use this one. Here you are extending parent object, and child object to a new object.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With