In JavaScript, the Array.pop() method is used to remove the last element from an array and returns that element. It modifies the original array by decreasing its length by one. This method can only remove one element in a single attempt.
By using this method, we can remove the element from the "end of an array". If the array is empty, it returns "undefined" as the result.
If we want to remove the first element of an array, use the JavaScript Array.shift() method.
Following is the syntax of JavaScript Array pop() Method −
array.pop();
This method does not accept any parameters.
This method returns the removed element, which is the last element of the array. If the array is empty, pop() returns undefined.
In the following example, we are using the JavaScript Array pop() method to remove the last element from the array.
<html> <body> <p id="demo"></p> <script> const animals = ["Lion", "Cheetah", "Tiger", "Elephant"]; animals.pop(); document.getElementById("demo").innerHTML = animals; </script> </body> </html>
Lion,Cheetah,Tiger
Here, we are removing the last element of the array and fetching the element that has been removed −
<html> <body> <p id="demo"></p> <script> const animals = ["Lion", "Cheetah", "Tiger", "Elephant"]; animals.pop(); document.getElementById("demo").innerHTML = animals; </script> </body> </html>
Lion,Cheetah,Tiger
If the array is empty and we try to use the pop() method on it, this method will return undefined as a result.
<html> <body> <p id="demo"></p> <script> const animals = []; let removed_element = animals.pop(); document.getElementById("demo").innerHTML = removed_element; </script> </body> </html>
undefined