What's the difference between a regular push and an Array.prototype.push.apply

user3092075 picture user3092075 · Feb 25, 2016 · Viewed 11.9k times · Source

I don't quite understand the difference between the following two lines of code. In my code, the line with "apply" works the way I want it to, and the line with just regular push doesn't.

So what is really going on when both of these are executed:

//this one does not work the way i want it to
$scope.items.push(result.data.stuff)

//this one works!
Array.prototype.push.apply($scope.items, result.data.stuff);

Edit: sorry for confusion, I fixed it so that it has the "push" method in there

Answer

Daniel A. White picture Daniel A. White · Feb 25, 2016

New 1. That pushes the array onto items.

$scope.items = [1, 2];
result.data.stuff = [3, 4];
$scope.items.push(result.data.stuff);
$scope.items[0] === 1;
$scope.items[1] === 2;
$scope.items[2][0] === 3;
$scope.items[2][1] === 4;

Old 1. Drops the existing reference that was in $scope.items.

$scope.items = [1, 2];
result.data.stuff = [3, 4];
$scope.items = result.data.stuff;
$scope.items[0] === 3;
$scope.items[1] === 4;

2. Pushes all the items from result.data.stuff into $scope.items, keeping the existing items.

$scope.items = [1, 2];
result.data.stuff = [3, 4];
Array.prototype.push.apply($scope.items, result.data.stuff);
$scope.items[0] === 1;
$scope.items[1] === 2;
$scope.items[2] === 3;
$scope.items[3] === 4;