Deep Arora
Deep Arora

Reputation: 2040

Why angular.extend is used as an input parameter to javascript push function?

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?

Upvotes: 0

Views: 612

Answers (2)

Hmahwish
Hmahwish

Reputation: 2232

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]

Upvotes: 0

Arun P Johny
Arun P Johny

Reputation: 388316

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).

Upvotes: 3

Related Questions