How to join two arrays in JavaScript
Joining two arrays in JavaScript can be done using the concat() method or the spread operator.
Using the concat() method
The concat() method is used to merge two or more arrays. It does not change the existing arrays, but instead returns a new array containing the elements of the original arrays.
var array1 = [1, 2, 3];
var array2 = [4, 5, 6];
var combinedArray = array1.concat(array2);
console.log(combinedArray); // Output: [1, 2, 3, 4, 5, 6]
Using the spread operator
The spread operator (…) can also be used to merge arrays. It allows us to expand an array into individual elements.
var array1 = [1, 2, 3];
var array2 = [4, 5, 6];
var combinedArray = [...array1, ...array2];
console.log(combinedArray); // Output: [1, 2, 3, 4, 5, 6]
Both methods are effective ways to combine two arrays in JavaScript. The choice between them depends on personal preference or the specific requirements of the code.