Array Methods

Inserting Elements

🙋 Need help? Ask an expert now!

All arrays in JavaScript are dynamic, meaning their size can be changed at runtime. New elements can be inserted to the array, and elements can be removed from the array as well if needed. The two methods we're going to introduce for inserting a value into an array is the push() method and the unshift() method. The function and syntax of the methods are shown below.


  • Inserts a new element at the tail of the array


  • Inserts a new element at the head of the array

The push() and unshift() both add an element to the original array. As mentioned above, the push() method adds the element to the end of the array. This is why version 1 of the array is [2,3,4,5]. The unshift() method on the other hand adds the element to the start of the array. Therefore, version 2 of the array ends up being [1,2,3,4,5]. These two method are two separate methods and should be used only when it is appropriate. You will probably end up using the push() method more often, but don't use these two methods interchangeably.

Edit Me on GitHub!

Application Question

Consider the following code segment:

var arr = [1, 2, 3, 4, 5];

What will the following code segment print to the console?