JS Array Concat vs Spread syntax. what kind of scenarios do we want to use them?

JavaScript array Concat method used to marge two more arrays. This method does not change existing arrays. The same task we can do using spread syntax by destructuring arrays. Consider:



Both results are the same. So, what kind of scenarios we want to use them? And which one is best for performance?

In general, you would use concat when you have two (or more) arrays from arbitrary sources, and you would use the spread syntax in the array literal if the additional elements that are always part of the array are known before. So if you would have an array literal with concat in your code, just go for spread syntax, and just use concat.

On the other hand, concat and spreads are very different when the argument is not an array. The two alternatives behave quite differently when dealing with non-array values.

When the argument is not an array, concat adds it as a whole, while tries to iterate it and fail if it can't. Consider:

To sum up, when your arguments are possibly non-arrays, the choice between concat and ... depends on whether you want them to be iterated. For performance concat is faster, probably because it can benefit from array-specific optimizations, while ... has to follow the common iteration protocol. Here you can see a performance Test.

Thank you for reading the post.



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store