Angular Copy vs Angular Extend

Posted By : Milind Ahuja | 29-Oct-2017

During your work in AngularJS, you definetely came across the situation when you want to copy one object to another. In such situation, you only have two options: angular.copy() or angular.extent().

Now let's see the difference between these two:

1. angular.copy(source, destination) :  This is to deep or full copy the properties of source object or array. There will be two objects which are pointing to two different memory locations.

Example:

var obj1 = { name: 'John', age: 27, skill: {} };
var obj2 = angular.copy(obj1);

console.log(obj2);
// Output: { name: 'John', age: 27, skill: {} }

console.log(obj1 === obj2);
// Output: false

console.log(obj1.skill === obj2.skill);
// Output: false
// obj2.skill is a copy of obj1.skill. They don't point to the same skill object.

 

2. angular.extend(destination, src1, src2 …) : This will create a shallow copy from one or more source objects to destination object and the destination will have all the properties from all the sources.

Example:

var src1 = { name: 'John', age: 30 }; // source 1
var src2 = { age: 26, skill: {} }; // source 2
var dst = {}; // destination

console.log(angular.extend(dst, src1, src2));
// Output: { name: 'John', age: 26, skill: {} }

console.log(src2.skill === dst.skill);
// Output: true
// src2 and dst share the same skill object due to shallow copy.

 

Now, which one should you use?

The correct answer to the above question is not between which one to use, but rather which one is required. And the best person to answer this is the developer himself.

So, based on your usage, you can choose between angular.copy or angular.extend

THANKS

About Author

Author Image
Milind Ahuja

Milind is a bright Lead Frontend Developer and have knowledge of HTML, CSS, JavaScript, AngularJS, Angular 2+ Versions and photoshop. His hobbies are learning new computer techniques, fitness and interest in different languages.

Request for Proposal

Name is required

Comment is required

Sending message..