Combine Two Arrays Using JavaScript

Introduction
How do you combine two arrays using JavaScript?
There are two ways to combine two arrays.
The modern technique is to use the ES6 spread operator like this: [...firstArray, ...secondArray].
And the second technique is to use the concat() method like this: firstArray.concat(secondArray).
Let's run through a quick code example for each.
Table of Contents
ES6 Spread Operator
Spread syntax allows an iterable like an array or string to be expanded in places where a N number of arguments (function calls) or elements (array literals) are expected. And it is commonly used in places where you want to use the elements of an array as arguments to a function.
Here's an example of how you'd use it in your JavaScript code:
JavaScript
 
const firstArray = ["Arbys", "McDonalds", "Wendys"]
const secondArray = ["Taco Bell", "Chick-fil-A"]
 
const combined = [...firstArray, ...secondArray]
If you log the combined variable that was created in the code above, a new array with all the values combined will be logged:
Output
 
[ "Arbys", "McDonalds", "Wendys", "Taco Bell", "Chick-fil-A" ]
It is worth noting that the spread operator will not work in Internet Exporer browsers.
Make sure you check the browser compatibility before using this in your code.
In the next section, we'll show a second method of using concat().
Concat()
The concat() method is used to merge two or more arrays and is built directly into the JavaScript language. It doesn't change anything about the existing arrays and just simply combines them into one new array.
Here's a full example of the concat() method:
JavaScript
 
const firstArray = ["Arbys", "McDonalds", "Wendys"]
const secondArray = ["Taco Bell", "Chick-fil-A"]
 
const combined = firstArray.concat(secondArray)
If you log the combined variable, one array with all the values combined will be logged just like the last example:
Output
 
[ 'Arbys', 'McDonalds', 'Wendys', 'Taco Bell', 'Chick-fil-A' ]
Unlike the spread operator method, note that this method is supported in all browsers including Interet Explorer.
Conclusion
There you have it! Two ways to combine two arrays in JavaScript. Make sure you check the browser compatibility for each method before using it in your code or on your website.
Thanks for reading and happy coding!