How to Extend an Existing JavaScript Array with Another Array Without Creating a New Array
Read this JavaScript tutorial and learn about several useful methods for extending an existing an Array with another array without creating a new array.
There are multiple widely used methods that will extend an existing JavaScript Array with another one without creating a new Array. This tutorial will help you resolve this issue right away.
push()
The push() method is generally used to push an array to the end of an existing one. In ES5 specification, this is often done as follows:
ES5: Using apply()
If your browser supports ES6, you can use the spread operator:
ES6+: Using the Spread Operator
Note that Function.prototype.apply() is largely obsolete in modern JavaScript. The spread operator is the preferred and more readable approach for passing array elements as arguments.
concat()
You can use the concat() method to extend an existing array in JavaScript:
JavaScript concat method
Beware that the <kbd class="highlighted">concat()</kbd> method returns a new array instead of modifying the existing one. The assignment num1 = num1.concat(num2) reassigns the variable to a newly created array rather than mutating the original in place. Therefore, it does not fulfill the "without creating a new array" requirement of this tutorial.