Extending an array with another array in JavaScript

Do you understand array.push.apply()?

Extending an array with another array in JavaScript

Do you know how to extend an array with another array in JavaScript?

Short Answer: Use array.push.apply(array, anotherArray)

const arr = [1, 2];
arr.push.apply(arr, [3, 4]); // HERE!
console.log(arr); // [1, 2, 3, 4]
This looks confusing, right? Read on this article to know the rationale behind the code.

Detailed Answer:

Relationship among the important objects.

In the above code, arr.push() is the same as Array.prototype.push(), and its signature is Array.prototype.push([element1[, ...[, elementN]]]). The function takes as input an arbitrary number of elements to append at the end of the array. So, if you tried arr.push([3, 4]), the arr would be [1, 2, [3, 4]]. But what you want to get is [1, 2, 3, 4], what to do then?

Function.prototype.apply()comes to rescue. Array.prototype.push is a function object, so it has a prototype that in turn has apply() as a method. The signature is Function.prototype.apply(thisArg, [argsArray]). apply() takes as input thisArg, which is an object treated as the value of this when executing the function, and an optional argsArray, which will be expanded when executing the function.

arr.push.apply(arr, [3, 4]); // converted to arr.push(3, 4);
console.log(arr); // [ 1, 2, 3, 4 ]

arr.push(5, 6);
console.log(arr); [ 1, 2, 3, 4, 5, 6 ]

arr.push(...[7, 8]); // You can also use the spread syntax ...
                     // This is also converted to arr.push(7, 8);
console.log(arr); [ 1, 2, 3, 4, 5, 6, 7, 8 ]

Reference

nodejs/node
Node.js JavaScript runtime :sparkles::turtle::rocket::sparkles: - nodejs/node
Study the specs of Function.prototype.apply() by seeing the test cases