0

I have recently found the following code on the Ionic codePen:

  $scope.add = function() {
    var nextMessage = messageOptions[messageIter++ % messageOptions.length];  // some string
    $scope.messages.push(angular.extend({}, nextMessage));
}

Why did the developer used angular.extend({}, nextMessage) as an input parameter of to javascript push function instead of directly passing the nextMessage as an argument?

3
  • Why do not you read documentation docs.angularjs.org/api/ng/function/angular.extend. Here you will get exact answer Commented Aug 18, 2015 at 6:26
  • I understand that the angular.extend extend the destination by copying properties of src. My main question is why it was required to create a copy in the above code? Why can't just directly pass the nextMessage as an argument? Commented Aug 18, 2015 at 6:32
  • 1
    angular.extend({}, nextMessage) this line of code, would be useful if you are updating the current object properties with new object with same reference. But in case of array $scope.message.push(nextMessage) should work perfectly. Commented Aug 18, 2015 at 6:46

2 Answers 2

3

It is used to create a copy nextMessage object and push that copy to the array.

angular.extend()

Extends the destination object dst by copying own enumerable properties from the src object(s) to dst. You can specify multiple src objects. If you want to preserve original objects, you can do so by passing an empty object as the target: var object = angular.extend({}, object1, object2).

Sign up to request clarification or add additional context in comments.

2 Comments

I understand that the angular.extend extend the destination by copying properties of src. My main question is why it was required to create a copy in the above code? Why can't just directly pass the nextMessage as an argument?
@DeepArora it might be because... when somebody manipulates the object in the array because of logical reasons the original object may not be modified
0

Javascript's Array.push() method will push items, not extend arrays.

var array1 = [1, 2, 3, 4];
var array2 = ['a', 'b'];
array1.push.apply(array1, array2);
console.log(foo); // will output [1, 2, 3, 4, "a", "b"]

angular.extend() method will extend arrays/objects, not push items.

var array1 = [1, 2, 3, 4];
var array2 = ['a', 'b'];
angular.extend(array1, array2);
console.log(foo); // will output ["a", "b", 3, 4]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.