Array.prototype.pop(), push(), shift(), and unshift()

whit1088

Jade

Posted on October 17, 2021

Array.prototype.pop(), push(), shift(), and unshift()

Introduction

These javascript methods are used to re-arrange an existing array or object in various ways and return a new value. Let's take a look at how each one functions.

Array.prototype.unshift()

This method adds values that have been input to the beginning of an array. It then returns the new array's length. Calling the array afterwords will have the new values shown in the array.

Example 1

unshift() outputs:

5

[ 'flour', 'chocolate', 'eggs', 'butter', 'milk' ]
Enter fullscreen mode Exit fullscreen mode

Array.prototype.shift()

This method takes the first value, also known as the value in the 0th index, and removes it from the array. The other values move down in order to make up for the lost space, and the removed value is then returned to an assigned variable.

Example 2

Note, this method will only work for arrays and objects with two or more values or it will return undefined.

shift() outputs

[ 'butter', 'milk' ]
eggs
Enter fullscreen mode Exit fullscreen mode

Array.prototype.push()

This method works the exact same way as Array.prototype.unshift() but rather than adding values to the front of the array, it will be added to the end.

Example 3

push() outputs

5
[ 'eggs', 'butter', 'milk', 'flour', 'chocolate' ]
Enter fullscreen mode Exit fullscreen mode

Array.prototype.pop()

This method also works nearly the exact same as Array.prototype.shift(), but removes and returns the last value instead of the first one.

Example 4

pop() outputs

[ 'eggs', 'butter' ]
milk
Enter fullscreen mode Exit fullscreen mode
💖 💪 🙅 🚩
whit1088
Jade

Posted on October 17, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related