JavaScript | Array pop()

arr.pop() function is used to remove the last element of the array and also returns the removed element. This function decreases the length of the array by 1. The syntax of this function is as follows:

arr.pop()

Arguments
This function does not have any argument.

Return value
This function returns the removed element. If the array is empty, then this function returns undefined.

Examples for the above function are provided below:

Example 1:

var arr = [34, 234, 567, 4];
var popped = arr.pop();
print(popped);
print(arr);

Output:

4
34,234,567

In this example the function pop() removes the last element from the array, which is 4 and returns it.

Example 2:

var arr = [];
var popped = arr.pop();
print(popped);

Output:

undefined

In this example the function pop() tries to extract the last element of the array but since the array is empty therefore it returns undefined as the answer.

Codes for the above function are provided below:

Program 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

<script>
// JavaScript code to illustrate pop() function
  
function func() {
    var arr = [34, 234, 567, 4];
  
    // popping the last element from the array 
    var popped = arr.pop();
    document.write(popped);
    document.write("<br>");
    document.write(arr);
}
func();
</script>

chevron_right


Output:

4
34,234,567

Program 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

// JavaScript to illustrate pop() function
<script>
function func() {
  
    var arr = [];
  
    // popping the last element
    var popped = arr.pop();
    document.write(popped);
}
func();
</script>

chevron_right


Output:

undefined


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.