Javascript Array Methods: push() and pop()

Javascript Array Methods: push() and pop()

Javascript Array Methods: push() and pop()

push() and pop() are the javascript array methods.

When you want to add or remove an item from the end of an array, push() and pop() methods will be used.

And when you want to add or remove an item from the beginning of an array, shift() and unshift() methods will be used. Read my other article about shift() and unshift() method. Javascript Array Methods: shift() and unshift()

Javascript Array: push() method.

push() function adds one or more items to the end of an array and returns the new length of the array.

1) Pushing a single item 

<br />var array= ["A", "B", "C", "D"];<br /><br />var newLength= array.push("E");<br /><br />console.log(newLength);<br />//OUTPUT: 5<br /><br /><br />console.log(array);<br />//OUTPUT: ["A", "B", "C", "D", "E"]<br /><br />

2) Pushing multiple items

we can also pass multiple items to push() method. which will add multiple items to the end of an array.

<br />var array= ["A", "B", "C"];<br /><br />var newLength= array.push("D","E");<br /><br />console.log(newLength);<br />//OUTPUT: 5<br /><br /><br />console.log(array);<br />//OUTPUT: ["A", "B", "C", "D", "E"]<br /><br />

Javascript Array: pop() method.

pop() function removes the last item of an array and returns a new length of an array and returns the removed item.

<br />var array= ["A", "B", "C", "D"];<br /><br />var element= array.pop();<br />console.log(element);<br />//OUTPUT: D<br /><br />console.log(array);<br />//OUTPUT: ["A", "B", "C"]<br /><br /><br />element= array.pop();<br />console.log(element);<br />//OUTPUT: C<br /><br />console.log(array);<br />//OUTPUT: ["A", "B"]<br /><br />

When the array is empty.

When the array is empty and pop() method is called, it’ll return undefined.

<br />var array= ["A", "B"];<br /><br />var lastElement= array.pop();<br />console.log(lastElement);<br />//OUTPUT: B<br /><br />console.log(array);<br />//OUTPUT: ["A"]<br /><br /><br />lastElement= array.pop();<br />console.log(lastElement);<br />//OUTPUT: A<br /><br /><br />console.log(array);<br />//OUTPUT: []<br /><br /><br />lastElement= array.pop();<br />console.log(lastElement);<br />//OUTPUT: undefined<br /><br /><br />console.log(array);<br />//OUTPUT: []<br /><br />

Here in the above code, you can see that we have called pop() method 3 times and when the last method is called, it returns the value undefined. because there is no item in the array.

Also Read:

Leave a Comment