This post will discuss how to insert multiple values into an array in JavaScript.

1. Using ES6 Spread operator with slicing

The recommended approach is to use the ES6 Spread operator with slicing for inserting multiple values into an array. The idea is to split the array into two subarrays using the index where specified values need to be inserted. Then we insert the specified values between the two subarrays with the help of the Spread operator. The following code example shows how to implement this.

Download  Run Code

2. Using Array.prototype.splice() function

Alternatively, you can use the splice() method, which can change the array’s contents by adding new elements in-place. Here’s what the code would look like:

Download  Run Code

 
Note that the code modifies the original array, and no copy is made. The code can be simplified using the Spread operator:

Download  Run Code

3. Using Array.prototype.push() function

To add elements at the end of an array, you can use the push() method with spread syntax.

Download  Run Code

4. Using Array.prototype.unshift() function

Similarly, to add elements at the beginning of an array, you can use the unshift() method with spread syntax.

Download  Run Code

That’s all about inserting multiple values into an array in JavaScript.