Array.prototype.pop(), push(), shift(), and unshift()
Jade
Posted on October 17, 2021
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.
unshift() outputs:
5
[ 'flour', 'chocolate', 'eggs', 'butter', 'milk' ]
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.
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
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.
push() outputs
5
[ 'eggs', 'butter', 'milk', 'flour', 'chocolate' ]
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.
pop() outputs
[ 'eggs', 'butter' ]
milk
Posted on October 17, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.