ngLover
ngLover

Reputation: 4578

How does this internally work to merge arrays using prototype in javascript?

How does it work ? i gone through this documentation but still not clear about its functionality according to me new array should get pushed at index no 4 and length should be 3 then how they are appended with length 6.

var a = [4,5,6];
var b = [7,8,9];
Array.prototype.push.apply(a, b);

can someone explain it in a better way because i have gone through several post but still not clear about it's working. More Info

Upvotes: 0

Views: 50

Answers (2)

Grissom
Grissom

Reputation: 1082

apply runs the function in context of first argument and another argument is list of parameters that will be passed to function. In your case it's similar to call a.push(7,8,9)

Upvotes: 0

shubham2102
shubham2102

Reputation: 26

Array.prototype.push.apply(a, b);

In this statement Array object's push method is invoked keeping Array 'a' the context and Array 'b' as the array of arguments for the function push of Array prototype.

So, this statement simply pushes the elements of Array 'b' into Array 'a'. And returns the length of the resultant array, which will be 6 in this case.

Try swapping the a with b and logging them.

For any doubt see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply

Upvotes: 1

Related Questions