JavaScript Program to Insert Item in an Array

To understand this example, you should have the knowledge of the following JavaScript programming topics:


Example 1: Add Item to Array Using splice()

Output

[1, 2, 3, 8, 4, 5]

In the above program, the splice() method is used to insert an item with a specific index into an array.

The splice() method adds and/or removes an item.

In the splice() method,

  • The first argument specifies the index where you want to insert an item.
  • The second argument (here 0) specifies the number of items to remove.
  • The third argument specifies the element that you want to add to an array.

Example 2: Add Item to Array Using for Loop

Output

[1, 2, 3, 8, 4]

In the above program,

  • The for loop is used to iterate through the array elements.
  • The element is added to the given index.
  • All the elements whose index is greater than the given index are shifted one step to the right.