W3docs

How to Insert an Item into an Array at a Specific Index

Read this JavaScript tutorial and learn the right method of inserting an item into an array at a specific index. Try examples and copy the code right away.

In this snippet, we are going to discuss a question concerning JavaScript array. Today’s topic covers the insertion of an item into the existing array at a specific index. However, there is no inbuilt method that directly allows inserting an element at any arbitrary index of the array.

One of the methods is the splice function. The <kbd class="highlighted">array.splice()</kbd> array method is used to add or remove items from an array taking three arguments: the index where the element should be inserted or removed, the number of items that should be deleted, and the new items that should be inserted.

The insertion will be setting the number of elements to be deleted to 0.

Javascript array insert element

function insertAt(array, index, ...elementsArray) {
  array.splice(index, 0, ...elementsArray);
}

In the example, we create an array and add an element to it into index 2:

Javascript array insert element

javascript— editable

Javascript Array

Array indices must be integers. Using non-integer strings with bracket notation creates object properties rather than array indices. Neither the length of an array nor the types of its elements are fixed. JavaScript arrays are zero-indexed. It means that the first element is at index 0, and the index of the last element is equal to the value of the array's length property minus 1.