This post will discuss how to insert an item at a specific index in an array using JavaScript.

1. Using Array.prototype.splice() function

The splice() method can be used to modify the array by removing or replacing existing elements and/or adding new elements in-place.

The following code demonstrates how to use the splice() method to insert an item at the specified index in the array:

Download  Run Code

2. Using ES6 Spread operator with slicing

The splice solution modifies the original array. If you don’t want to change the original array, create a new array using the ES6 Spread operator with slicing.

The idea is to split the array into two subarrays using the index where specified values need to be inserted. Then we put the specified value between two subarrays with the help of the Spread operator. Here’s what the code would look like:

Download  Run Code

3. Using Array.prototype.push() function

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

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.

Download  Run Code

That’s all about inserting an item at a specific index in an array using JavaScript.