Array.concat() VS spread operator!

Dario Chiapperini


Dario Chiapperini
Array.concat() VS spread operator!
In this post I will show you the differences of these two methods. Basically, the purpose of both is to add one or more elements to an array like below:
const a = ["banana", "apple", "pear"];
const b = "orange";
console.log(a.concat(b)); //result --> ["banana", "apple", "pear", "orange"]
console.log([...a, b]); // result --> ["banana", "apple", "pear", "orange"]
In this example, both of these have the same result. So what are the differeces? Let's try with another example:
console.log([...a, ...b]); // result --> ["banana", "apple", "pear", 'o', 'r', 'a', 'n', 'g', 'e'];
This happens, because the 'spread operator' (...) literally 'spreads' the string to letters and add it to the array.
This is not true in any cases. If in 'b' variable is assigned a number, only the concat() method is possible, because spread operator isn't able to iterate throught a number.
const a = ["banana", "apple", "pear"];
const b = 30;
console.log(a.concat(b)); // result --> ["banana", "apple", "pear", 30]
console.log([...a, ...b]); // result --> Uncaught TypeError: b is not iterable