What are the benefits of using the 'concat' method over 'push' for concatenating arrays in JavaScript?

concat(array) vs push(...array)

I’ve been using .push(...) method to concatenate 2 arrays unpacking the second array, using the three dots notation, and passing that as the argument (array1.push(...array2)). But I just noticed that .concat(...) does the same thing, at least as far as I know.

I just want to know what are the benefits of using one over the other, if any, aside from .concat(...) being more idiomatic.

>Solution :

JavaScript engines typically put a cap on the number of arguments you can pass to a method before they throw an error, for example, the below throws an error in Chrome:

const arr = Array(150000).fill(0);
const arr2 = [];
arr2.push(...arr);

Whereas when using .concat(), you’ll only be passing the one array to the method, so you don’t get the error:

const arr = Array(150000).fill(0);
const arr2 = [];
const res = arr2.concat(arr);
// res is an array with 150000 `0`s

Additionally, with .push() + ..., you’re effectively doing two iterations over your iterable/array, one for unpacking its contents as arguments to the .push() method, and then another for one done internally by the .push() method itself to iterate through each of the arguments and append it to the target array.

Another noticeable difference is in what both methods return, .concat() will return a new array and won’t modify the target, which can be useful in methods such as .map() or .reduce() where you need to produce a new array with mutating the original. Whereas .push() will return the length of the updated array and will modify the target, so that is another difference to consider.

Leave a Reply