AngularJS : copy vs extend

06 / Feb / 2014 by Sakshi Tyagi 9 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 (9)

  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. Sudheer Verma

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

    Reply

Leave a comment -