Code Whisperer Code Whisperer - 22 days ago 7
AngularJS Question

Should I Use Angular.copy() or _.clone()?

I'm working on a project that has both Angular and Underscore as a dependency.

When I need to create a copy of an object, depending on my mood at the time, I might use

angular.copy()
or
_.clone()


It occurs to me that one of these methods is probably more fast/reliable/robust than the other.

Are there any known issue with either of these functions that make it better or worse to use than the other, assuming both libraries are already included?

Answer

Regarding your question: angular.copy and _.clone are different. It's not a question of which is better, it is about what you need as @Kevin B stated in the comments.

angular.extend() on the other hand, is a shallow copy akin to _.clone

Angular.copy vs Angular.extend

Performance wise, i'm not sure which is better, but for opinions sake, i'm opposed to including libraries into the global scope (underscore) with any angular app, as usually these things are written as angular modules. angular.copy/angular.extend would win in this case.

Shallow/Deep Copy:

Its very simple that if the object has only primitive fields, then obviously you will go for shallow copy but if the object has references to other objects, then based on the requiement, shallow copy or deep copy should be chosen. What I mean here is, if the references are not modified anytime, then there is no point in going for deep copy. You can just opt shallow copy. But if the references are modified often, then you need to go for deep copy. Again there is no hard and fast rule, it all depends on the requirement.

Source