How can I add new array elements at the beginning of an array in Javascript? How can I add new array elements at the beginning of an array in Javascript? javascript javascript

How can I add new array elements at the beginning of an array in Javascript?


Use unshift. It's like push, except it adds elements to the beginning of the array instead of the end.

  • unshift/push - add an element to the beginning/end of an array
  • shift/pop - remove and return the first/last element of an array

A simple diagram...

   unshift -> array <- push   shift   <- array -> pop 

and chart:

          add  remove  start  end   push    X                   X    pop           X            Xunshift    X             X  shift           X      X

Check out the MDN Array documentation. Virtually every language that has the ability to push/pop elements from an array will also have the ability to unshift/shift (sometimes called push_front/pop_front) elements, you should never have to implement these yourself.


As pointed out in the comments, if you want to avoid mutating your original array, you can use concat, which concatenates two or more arrays together. You can use this to functionally push a single element onto the front or back of an existing array; to do so, you need to turn the new element into a single element array:

const array = [3, 2, 1]const newFirstElement = 4const newArray = [newFirstElement].concat(array) // [ 4, 3, 2, 1 ]console.log(newArray);