JavaScript: How to append/prepend/insert elements to an array

Updated: March 20, 2023 By: Khue Post a comment

This short and straightforward article shows you how to append, prepend, and insert new elements to an existing array in modern JavaScript.

Appending Elements

Appending a Single Element

In order to append an element to the end of an array, you can use the push() method as shown in the example below:

const arr = [1, 2, 3]


[ 1, 2, 3, 4 ]

Appending another Array to an Existing Array

There might be times when you need to append another array to the end of an existing array. The solution is to use the concat() method, like so:

const arr1 = ['Elden Ring', 'Cyberpunk 2077', 'Valorant']
const arr2 = ['Dark Souls', 'The Witcher', 'Counter-Strike']

const arr3 = arr1.concat(arr2)


  'Elden Ring',
  'Cyberpunk 2077',
  'Dark Souls',
  'The Witcher',

Another way is to use the spread operator:

const arr3 = [...arr1, ...arr2];

Prepending Elements

Prepending a Single Element

To prepend a given element to the beginning of an array, you can use the unshift() method.


const arr = ['steel', 'wooden', 'fire']
arr.unshift('sling academy')


[ 'sling academy', 'steel', 'wooden', 'fire' ]

Prepending another Array to an Existing Array

To prepend another array to a given array, we will use the concat() method.


const arr1 = [1, 2, 3]
const arr2 = [-3, -2, -1, 0]

// prepend arr2 to arr1
const arr3 = arr2.concat(arr1)


  -3, -2, -1, 0,
   1,  2,  3

The same result can be produced by using the spread operator:

const arr3 = [...arr2, ...arr1]

Inserting Elements

Inserting a Single Element at a Specific Index

To insert an element at a specific index of an array, you can use the splice() method.


const arr = ['a', 'b', 'c']

// insert D at index 1
arr.splice(1, 0, 'D'); 


[ 'a', 'D', 'b', 'c' ]

The index of the old element b at the inserted position will be increased by 1.

Inserting another Array into an Existing Array

To insert another array at a specific index of an existing array, you can also use the splice() method with spread syntax in combination.


const arr1 = ['car', 'bike', 'plane']
const arr2 = ['Lion', 'Tiger', 'Bear'];

// insert arr2 into arr1 at index 1
arr1.splice(1, 0, ...arr2);



[ 'car', 'Lion', 'Tiger', 'Bear', 'bike', 'plane' ]

That’s it. The tutorial ends here. Happy coding & have a nice day!