Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best practice to extend objects in underscore.js

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?

like image 586
Sebastian Avatar asked Mar 08 '15 15:03

Sebastian


People also ask

Is underscore js still used?

Lodash and Underscore are great modern JavaScript utility libraries, and they are widely used by Front-end developers.

How does _ Extend Work?

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.

Why is JavaScript underscore better?

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.

Is Lodash still needed 2022?

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.


1 Answers

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.

like image 148
syed imty Avatar answered Sep 24 '22 08:09

syed imty