0

I tried to merge two arrays in JavaScript. I wrote a code like this:

var array1 = [1, 2];

var array2 = [3, 4];

array2.forEach(function(value) {
   array1.push(value);
});

I know there are better ways such as array1 = array1.concat(array2); and this question is not about it.

I tried to minimize the above code like this:

var array1 = [1, 2];

var array2 = [3, 4];

array2.forEach(array1.push);

It is same code but I do not create the extra unnamed function. I pass array1.push function directly to forEach. I expected same result but I get this exception:

Cannot convert undefined or null to object

I do not understand why I am getting this exception?

Arashsoft
  • 2,749
  • 5
  • 35
  • 58
  • You're passing the push function, and disconnecting it from the array you want to push into in the process. – Quentin May 16 '18 at 21:07
  • 1
    even if that would work with `array2.forEach(Array.prototype.push.bind(array1));` you get all parameters of the callback pushed, like value, index and array for each loop. – Nina Scholz May 16 '18 at 21:09
  • For the best performance just use namedFunction, because bind() on each interation is not perfect as well –  May 16 '18 at 21:40

0 Answers0