DEV Community

Nedy Udombat
Nedy Udombat

Posted on • Updated on

Understanding JavaScript Array Series XX - Array.unshift()

Yesterday, you asked a question saying What if I want to put back the element I have removed either from the start of the array or the end of the array?. Can't recall asking this? Check this article to refresh your memory.

Have you heard about the Array.unshift()? No?

This method adds a new element or a bunch of elements to the start of the array and returns the new length of the array. This is the opposite of Array.shift() as it adds to the beginning of the array, while Array.shift() removes from the beginning of the array.

Can you show me the syntax? Yeah sure.

const elem = arr.unshift(item1, item2, item3, ..., itemN);

[item1, item2, item3, ..., itemN]: These are the elements to be added to the array.

[arr]: This is the array you want to add the new elements to.

[elem]: This value holds the new length of the array after the successful addition of elements to the start of the array.

Cool, it is kind of similar to array.push(), except here it adds the element from the beginning of the array. Please, can you show us an example? Sure why not.

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

What happens if an array is passed as the argument to unshift()

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

In this case the entire array that is passed as an argument is passed as one argument to the array.

Conclusion:

  • Array.push(): Add items to the end of an array.
  • Array.pop(): Remove items from the end of an array.
  • Array.unshift(): Add items to the start of an array.
  • Array.shift(): Remove items from the start of an array.

That's all for today, see you next time.

Here is the link to the other articles on this Array series written by me:

Got any question, addition or correction? Please leave a comment.

Thank you for reading. 👍

Top comments (1)

Collapse
 
sanjeevpanday profile image
sanjeev

I think in the conclusion section, Array.shift() and Array.unshift() descriptions are different than actual behavior.