Member-only story
How To Merge Two Arrays in JavaScript
Use the .concat() method or the spread operator

Merging two arrays, whether the arrays already exist or the second array is yet to be defined, is a common task. Moreover, if you’re not careful then the merge may not function as you’d expect.
Let’s take a look at two arrays [1,2,3]
and [4,5,6]
that we want to merge to become [1,2,3,4,5,6]
. Your first instinct might be to use the +
sign or .push()
method, but neither of these yield the proper result.
a = [1,2,3]
b = [4,5,6]console.log(a + b); // [1,2,34,5,6]
console.log(a.push(b)); // [1,2,3,[4,5,6]
In the first example, the concatenation operator +
is treating each item as a string. As a result, the last item in a
and first item in b
are concatenated producing 34
.
In the second example, b
is treated as a single value and added to the end of a
producing a nested array.
To produce the array that we’re looking for, we need to use either the .concat()
method or the spread ...
operator.
The .concat() Method
This has long been the de-facto technique for concatenating arrays. The method is invoked from the parent array — the one that will be first in order — and accepts any number of…