How to add new elements at the beginning of an array in JavaScript?

Use unshift to add new elements at the beginning of an array. 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            X
unshift    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 = 4

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

console.log(newArray);

concat can also append items. The arguments to concat can be of any type; they are implicitly wrapped in a single-element array, if they are not already an array:

const array = [3, 2, 1]

const newLastElement = 0

// Both of these lines are equivalent:
const newArray1 = array.concat(newLastElement) // [ 3, 2, 1, 0 ]
const newArray2 = array.concat([newLastElement]) // [ 3, 2, 1, 0 ]

console.log(newArray1);
console.log(newArray2);

How to add new elements at the beginning of an array in JavaScript?

With ES6, using the spread operator ... :

Example

var arr = [23, 45, 12, 67];
arr = [34, ...arr]; // RESULT : [34,23, 45, 12, 67]

console.log(arr)

Using unshift

array operations image
var a = [23, 45, 12, 67];
a.unshift(34);
console.log(a); // [34, 23, 45, 12, 67]

If you want to push elements that are in an array at the beginning of your array, use <func>.apply(<this>, <Array of args>):

const arr = [1, 2];
arr.unshift.apply(arr, [3, 4]);
console.log(arr); // [3, 4, 1, 2]

How to add new elements at the beginning of an array in JavaScript using concat?

Another way to do that is through concat:

var arr = [1, 2, 3, 4, 5, 6, 7];
console.log([0].concat(arr));

The difference between concat and unshift is that concat returns a new array.

function fn_unshift() {
  arr.unshift(0);
  return arr;
}

function fn_concat_init() {
  return [0].concat(arr)
}

Here is the test result:

Enter image description here

Alternative method to add elements at the beginning of an array in JS

Without Mutating

Actually, all unshift/push and shift/pop mutate the source array.

The unshift/push add an item to the existed array from begin/end and shift/pop remove an item from the beginning/end of an array.

But there are few ways to add items to an array without a mutation. the result is a new array, to add to the end of array use below code:

const originArray = ['one', 'two', 'three'];
const newItem = 4;

const newArray = originArray.concat(newItem); // ES5
const newArray2 = [...originArray, newItem]; // ES6+

To add to begin of original array use below code:

const originArray = ['one', 'two', 'three'];
const newItem = 0;

const newArray = (originArray.slice().reverse().concat(newItem)).reverse(); // ES5
const newArray2 = [newItem, ...originArray]; // ES6+

With the above way, you add to the beginning/end of an array without a mutation.

Cheatsheet to prepend new element(s) into the array

1. Array#unshift

const list = [23, 45, 12, 67];

list.unshift(34);

console.log(list); // [34, 23, 45, 12, 67];

2. Array#splice

const list = [23, 45, 12, 67];

list.splice(0, 0, 34);

console.log(list); // [34, 23, 45, 12, 67];

3. ES6 spread…

const list = [23, 45, 12, 67];
const newList = [34, ...list];

console.log(newList); // [34, 23, 45, 12, 67];

4. Array#concat

const list = [23, 45, 12, 67];
const newList = [32].concat(list);

console.log(newList); // [34, 23, 45, 12, 67];

Note: In each of these examples, you can prepend multiple items by providing more items to insert.

Detailed explanations

Using Push Method to insert elements at the start of an array

The first and probably the most common JavaScript array method you will encounter is push(). The push() method is used for adding an element to the end of an array.

Let’s say you have an array of elements, each element being a string representing a task you need to accomplish. It would make sense to add newer items to the end of the array so that we could finish our earlier tasks first.

Let’s look at the example in code form:

const arr = ['First item', 'Second item', 'Third item'];

arr.push('Fourth item');

console.log(arr); // ['First item', 'Second item', 'Third item', 'Fourth item']

Alright, so push has given us a nice and simple syntax for adding an item to the end of our array.

Let’s say we wanted to add two or three items at a time to our list, what would we do then? As it turns out, push() can accept multiple elements to be added at once.

const arr = ['First item', 'Second item', 'Third item'];

arr.push('Fourth item', 'Fifth item');

console.log(arr); // ['First item', 'Second item', 'Third item', 'Fourth item', 'Fifth item']

Now that we’ve added some more tasks to our array we might want to know how many items are currently in our array to determine if we have too much on our plate.

Luckily, push() has a return value with the length of the array after our element(s) have been added.

const arr = ['First item', 'Second item', 'Third item'];

const arrLength = arr.push('Fourth item', 'Fifth item');

console.log(arrLength); // 5 
console.log(arr); // ['First item', 'Second item', 'Third item', 'Fourth item', 'Fifth item']

Using the Unshift Method to add elements at the start of an array in JavaScript

Not all tasks are created equal. You might run into a scenario in which you are adding tasks to your array and suddenly you encounter one which is more urgent than the others.

It’s time to introduce our friend unshift() that allows us to add items to the beginning of our array.

const arr = ['First item', 'Second item', 'Third item'];

const arrLength = arr.unshift('Urgent item 1', 'Urgent item 2');

console.log(arrLength); // 5 
console.log(arr); // ['Urgent item 1', 'Urgent item 2', 'First item', 'Second item', 'Third item']

You may notice in the example above that, just like the push() method, unshift() returns the new array length for us to use. It also gives us the ability to add more than one element at a time.

Using the Concat Method to add elements at the start of an array

Short for concatenate (to link together), the concat() method is used for joining together two (or more) arrays.

If you remember from above, the unshift() and push() methods return the length of the new array. concat(), on the other hand, will return a completely new array.

This is a very important distinction and makes concat() extremely useful when you’re dealing with arrays you do not want to mutate (like arrays stored in React state).

Here is what a fairly basic and straightforward case might look like:

const arr1 = ['?', '?'];
const arr2 = ['?', '?'];

const arr3 = arr1.concat(arr2);

console.log(arr3); // ["?", "?", "?", "?"] 

Let’s say you have multiple arrays you would like to join together. No worries, concat() is there to save the day!

const arr1 = ['?', '?'];
const arr2 = ['?', '?'];
const arr3 = ['?', '?'];

const arr4 = arr1.concat(arr2,arr3);

console.log(arr4); // ["?", "?", "?", "?", "?", "?"]

Cloning with Concat

Remember how I said that concat() can be useful when you don’t want to mutate your existing array? Let’s take a look at how we can leverage this concept to copy over the contents of one array into a new array.

const arr1 = ["?", "?", "?", "?", "?", "?"];

const arr2 = [].concat(arr1);

arr2.push("?");

console.log(arr1) //["?", "?", "?", "?", "?", "?"]
console.log(arr2) //["?", "?", "?", "?", "?", "?", "?"]

Awesome! We can essentially “clone” an array using concat().

But there is a small ‘gotcha’ in this cloning process. The new array is a “shallow copy” of the copied array. This means that any object is copied by reference and not the actual object.

Let’s take a look at an example to explain this idea more clearly.

const arr1 = [{food:"?"}, {food:"?"}, {food:"?"}]

const arr2 = [].concat(arr1);

//change only arr2
arr2[1].food = "?";
arr2.push({food:"?"})

console.log(arr1) //[ { food: '?' }, { food: '?' }, { food: '?' } ]

console.log(arr2) //[ { food: '?' }, { food: '?' }, { food: '?' }, 
{ food: '?' } ]

Even though we didn’t directly make any changes to our original array, the array was ultimately affected by the changes we made on our cloned array!

There are multiple different ways to properly do a “deep clone” of an array, but I will leave that for you as homework.

Summary

The terms shift/unshift and push/pop can be a bit confusing, at least to folks who may not be familiar with programming in C.

If you are not familiar with the lingo, here is a quick translation of alternate terms, which may be easier to remember:

* array_unshift()  -  (aka Prepend ;; InsertBefore ;; InsertAtBegin )     
* array_shift()    -  (aka UnPrepend ;; RemoveBefore  ;; RemoveFromBegin )

* array_push()     -  (aka Append ;; InsertAfter   ;; InsertAtEnd )     
* array_pop()      -  (aka UnAppend ;; RemoveAfter   ;; RemoveFromEnd )

In this article, we learned how to add new elements at the beginning of an array in JavaScript.

Hope you learned something from this post. The primary source of this article is StackOverflow.

Follow Programming Articles for more!

About ᴾᴿᴼᵍʳᵃᵐᵐᵉʳ

Linux and Python enthusiast, in love with open source since 2014, Writer at programming-articles.com, India.

View all posts by ᴾᴿᴼᵍʳᵃᵐᵐᵉʳ →