AngularJS : copy vs extend

06 / Feb / 2014 by Sakshi Tyagi 11 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:

[js]
var mySource = {‘name’ : ‘sakshi’, ‘age’ : ’24’, ‘obj’ :{‘key’:’value’}}
var myDest = {}
angular.copy(mySource, myDest);
console.log(myDest);
[/js]

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:

[js]
var mySource1 = {‘name’ : ‘neha’, ‘age’ : ’26’, obj2 : {}}
var mySource2 = {‘course’ : ‘MCA’}
var myDest = {}
angular.extend(myDest, mySource1,mySource2)
console.log(myDest);
[/js]

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.

Read Further on AngularJS Series

FOUND THIS USEFUL? SHARE IT

comments (11)

  1. Bruce

    Can you provide an example showing the content copied from one file into another file i.e) From source file to destination file using copy function?

    Reply
  2. Jessica Barnes

    This is a fantastic run through these. Very clear and simple, yet thorough, examples of each situation. About additional information about the Angularjs, hireangulardeveloperindia.com

    Reply
  3. 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
  4. Sudheer Verma

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

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *