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]
arr.push(4)
console.log(arr)

Output:

[ 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)
console.log(arr3)

Output:

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

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.

Example:

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

Output:

[ '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.

Example:

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

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

Output:

[
  -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.

Example:

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

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

Output:

[ '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.

Example:

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

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

console.log(arr1); 

Output:

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

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