skip to Main Content

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.

3

Answers


  1. The big difference that push() adds elements to an array, but concat() returns a new array.
    Recently after been working with Vue I found that it’s important keep object variables as intact as possible and declare them with const.

    This allows not losing references to the original objects and promotes reactive programming.
    For me currently that’s a very important concept. It allows me to be relaxed regarding whether any object reference could be broken if code is very modular.

    The only problem that spread arguments are slow and not save with big arrays so I wouldn’t mind to monkeypatch Array.prototype.append with my custom benchmarked implementation.

    For example:

    class Some{
      constructor(source){
        this.arr = source;
      }
      push(...elems){
        this.arr.push(...elems);
      }
    }
    
    let source = []; // that's bad for me, I use const now as much as possible
    
    const some = new Some(source);
    
    // step 1: using push
    source.push(...[0, 0, 0]);
    some.push(...[1, 1, 1]);
    
    console.log(source.join());
    console.log(some.arr.join());
    
    // step 1: using concat, here the original array link is lost
    source = source.concat([2, 2, 2]);
    
    // hmm, one would expect them to be equal...
    console.log(source.join());
    console.log(some.arr.join());

    An example how the appending could be implemented, it’s faster than pushing (there’s also some boost because of pre-allocating new elements).

        const arr = Array(10000000).fill(0);
        
        Array.prototype.append = function(arr){
        
            this.length += arr.length;
            for(let i = 0, j = this.length - arr.length; i < arr.length; i++, j++){
                this[j] = arr[i];
            }
            
            return this;
        
        };
        
        let start = performance.now();
        
        const dst = [];
            
        for(let i = 0; i < arr.length; i++){
            dst.push(arr[i]);
        }
        
        console.log(`pushing: ${performance.now() - start}`);
        
        start = performance.now();
        
        const dst2 = [];
            
        dst2.append(arr);
        
        
        console.log(`appending: ${performance.now() - start}`); 
    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
  3. I don’t understand if you want to add an Array into another or just make one Array made of two Arrays.

    In the las case this is a short way to concatenate Arrays too by using spread syntax :

                const arr1 = [1, 2, 3];
                const arr2 = [4, 5, 6];
                const combinedArray = [...arr1, ...arr2];
                console.log(combinedArray);

    Note :

    If you need to preserve the original arrays, this code above is suitable, like the concat() method.

    The push() method will modify your initial Array.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search