Array.prototype.concat()
and the spread operator are commonly used for the same purpose. However, there are a few differences between these two which we will discuss in this shot. But first, let’s recall what these methods are.
Array.prototype.concat()
Array.prototype.concat()
is used to merge two or more arrays. This method does not mutate the original array, but instead returns a new array populated with elements of all the arrays that were merged.
array 3 = array1.concat(array2);
The spread operator is denoted by three dots (...
). It unpacks elements of iterable objects such as arrays, sets, etc., and maps them into a list. We can use this operator to merge many iterable objects into one.
array3 = [...array1, ...array2];
concat()
and ...
act very different when the argument is not an array. If the argument is not an array, concat()
will add it as a whole, while ...
tries to iterate it and fails if it can’t.a = [1, 2, 3, 4]
b = 'edpresso';
console.log(a.concat(b)) // [1, 2, 3, 4, 'edpresso']
console.log([...a, ...b])
// [1, 2, 3, 4, 'e', 'd', 'p', 'r', 'e', 's', 's', 'o']
a = [1, 2, 3, 4]
b = 100;
console.log(a.concat(b)) // [1, 2, 3, 4, 100]
console.log([...a, ...b]) // TypeError: b is not iterable
concat()
is used to add the elements at the end of the array, while ...
is used to add elements anywhere in the array.a = [1, 2, 3, 4]
b = [5, 6, 7, 8]
console.log(a.concat(b)) // [1, 2, 3, 4, 5, 6, 7, 8]
console.log([...b, ...a]) // [5, 6, 7, 8, 1, 2, 3, 4]
concat()
will take the value from the generator as it is and will append to the array, while ...
will iterate over it and add each element independently.function* generate() {
yield 'edpresso';
}
console.log([.concat(generate())) // ['edpresso']
console.log([...generate()]) // ['e', 'd', 'p', 'r', 'e', 's', 's', 'o']
concat()
method is more efficient and fast when the array size is large. ...
is more efficient when the array size is small. Using ...
for large array size will give error of Maximum call stack size exceeded
, which can be avoided by using the concat()
method.