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:
Concat:
let number1= ['one', 'two', 'three'];
let number2 = ['four', 'five'];
console.log(number1.concat(number2));Expected Result: ["one","two","three","four","five" ]
Spread:
let number1= ['one', 'two', 'three'];
let number2 = ['four', 'five'];
console.log([...number1, ...number2]);Expected Result: ["one","two","three","four","five" ]
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:
const a = [1, 2, 3]
const x = 'hello';
console.log(a.concat(x)); // [ 1, 2, 3, 'hello' ]
console.log([...a, ...x]); // [ 1, 2, 3, 'h', 'e', 'l', 'l', 'o' ]
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.