Search code examples
javascriptarraysconcatenationpush

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 without 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.

    As pointed out by @T.J. Crowder, the iterator of arrays which is invoked when using the spread syntax ... does not preserve blanks in sparse arrays, instead it unpacks them as undefined values, meaning that if the array you're specifying is sparse when using .push() + ... you'll get undefined for the blanks, whereas the blanks will be preserved when using .concat() directly:

    const arr = Array(3); // this is a sparse array, [empty × 3], not to be confused with [undefined, undefined, undefined]
    const arr2 = [];
    arr2.push(...arr); // Here `...` becomes: arr2.push(undefined, undefined, undefined);
    console.log(arr2); // [undefined, undefined, undefined]
    
    const arr3 = [];
    console.log(arr3.concat(arr)); // Retains empties: [empty × 3]
    See browser console for results