AngularJS : copy vs extend

06 / Feb / 2014 by Sakshi Tyagi 10 comments

While using AngularJS, you will usually come across this situation when you want to copy one object to another object.

In such case you will have only two solutions: angular.copy() or angular.extend().

Lets see how these solutions work.

1. angular.copy(source, destination) : It creates a deep copy of source object or array and assign it to destination where ‘destination’ is optional. By writing deep copy, I mean that a new copy of the referred object is made.

For example:

var mySource = {'name' : 'sakshi', 'age' : '24', 'obj' :{'key':'value'}}
var myDest = {}
angular.copy(mySource, myDest);
console.log(myDest);

Output: {'name' : 'sakshi', 'age' : '24', 'obj' :{'key':'value'}}

If you check mySource.obj === myDest.obj, this will give a false result because both points to different objects. This is called deep copying.

2. angular.extend(destination, src1, src2 …) : It creates a shallow copy of one or more sources provided and assign them to destination.

For example:

var mySource1 = {'name' : 'neha', 'age' : '26', obj2 : {}}
var mySource2 = {'course' : 'MCA'}
var myDest = {}
angular.extend(myDest, mySource1,mySource2)
console.log(myDest);

Output: {name: "neha", age: "26", course: "MCA", obj2: Object}

Now if you check mySource1.obj2 === myDest.obj2, it will give a true result because both points to same reference of an object. This is called shallow copying.

NOTE: One thing to keep in mind is that angular.copy() is slower than angular.extend()

You can now use both these solutions and find out which one you like to use in the future.

FOUND THIS USEFUL? SHARE IT

comments (10)

  1. Jordan

    useful, thanks! but important to note that angular.extend doesn’t do a “deep” merge – you want to use angular.merge for that – both methods use angular’s baseExtend method, but angular.merge sets the baseExtend method’s “deep” argument to true which results in baseExtend updating the object tree recursively: https://github.com/angular/angular.js/blob/7757f0a9e3dff7b1feb9994d750b5251230936c8/src/Angular.js#L326 (don’t be confused by isObject – this will return true for arrays)

    Reply
  2. comptoir de quartz prix Quebec

    Just wish to say your article is as astounding. The clearness in your
    submit is just excellent and i can suppose you’re knowledgeable in this subject.
    Well along with your permission allow me to take hold of your RSS feed to stay up
    to date with drawing close post. Thanks a million and
    please carry on the rewarding work.

    Here is my web-site: comptoir de quartz prix Quebec

    Reply
  3. Sudheer Verma

    Nice explanation , Great help for one issue in our project where deep object was not maintaining state.

    Reply

Leave a comment - swati Cancel reply