DEV Community

elam0012
elam0012

Posted on

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

In this tutorial I am going to cover an important topic regarding different Array’s methods that a lot of us get confused when using it. I am going to cover the difference between pop(), push(), shift(), and unshift().

1.Pop( ):

pop() is an array method will return the last element in the array and actually delete it from the array, which will decrease the elements length by 1. If the array has only one Element, then the returned value will be “undefined”. This method can be used either with array of variables or Array of objects. The method Syntax is pop( ).

Example:
Enter fullscreen mode Exit fullscreen mode

Alt Text

Output:

Alt Text

2.Push( ):

Unlike pop(), the push( ) method will insert a new element(s) to the Array and place it at its end, and will return the new Array length. This will increase the Array length by adding the number of the inserted elements to the number of the original Array’s element(s) length. Means it can push only single element or number of elements at once. And like pop(), this method can be used either with array of variables or Array of objects The method Syntax is push(element0, …, elementN ).

Example:
Enter fullscreen mode Exit fullscreen mode

Alt Text

Output:

Alt Text

3.shift( ):

Opposite to pop( ), The shift( ) method will return the first element in the array and also delete it from the array. This will decrease the elements length by 1. If the array has only one Element, then the returned value will be “undefined”. This method can be used either with array of variables or Array of objects. The method Syntax is shift( ).

Example:
Enter fullscreen mode Exit fullscreen mode

Alt Text

Output:

Alt Text

4.unshift( ):

unshift( ) method will insert a new element(s) to the Array and place it at its beginning. It will return the new Array length. The method will increase the Array length by adding the number of the inserted elements to the number of the original Array’s element(s) length. Means it can add only single element or number of elements at once. And again, this method can be used either with array of variables or Array of objects The method Syntax is unshift(element0, …, elementN ).

Example:
Enter fullscreen mode Exit fullscreen mode

Alt Text

Output:

Alt Text

Top comments (0)