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
The big difference that
push()
adds elements to an array, butconcat()
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:
An example how the appending could be implemented, it’s faster than pushing (there’s also some boost because of pre-allocating new elements).
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:
Whereas when using
.concat()
, you’ll only be passing the one array to the method, so you don’t get the error: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.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 :
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.