JavaScript Array pop method is used to remove the last element from the JS Array and returns that element. This method will modify the Array length by 1.
Pop() is one of the methods to use to remove and add four methods. Others 3 methods are shift(), push() and unshift().
Syntax
A simple syntax of pop() method.
array.pop()
Parameters
No parameter are required.
Return value
A removed element from the array, if the array is empty than return value is undefined.
JavaScript Array pop Example
Let’s see how to remove the last element from the Array JavaScript example.
var fruits = ["Apple", "Orange", "Kiwi", "Cherry"];
fruits.pop();
In the example creating an array and then removing the last element. In the output, both arrays will show. Here we are using to show array in p tag, you can also use console log to see the output.
<!DOCTYPE html>
<html>
<body>
<p>Click on button, item from Array will remove</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<p id="count"></p>
<script>
var fruits = ["Apple", "Orange", "Kiwi", "Cherry"];
document.getElementById("demo").innerHTML = fruits;
document.getElementById("count").innerHTML = fruits.length;
function myFunction() {
fruits.pop();
document.getElementById("demo").innerHTML = fruits;
document.getElementById("count").innerHTML = fruits.length;
}
</script>
</body>
</html>
Output: below in GIF file.
Let’s print the Javascript array pop index value
A removed item index value will be “array.length – 1“, because this method removes the last element of the array and array indexing is start from 0.
Let’s see how to get the value of the removed element from array:-
var fruits = ["Apple", "Orange", "Kiwi", "Cherry"];
var popped = fruits.pop();
complete example:
<!DOCTYPE html>
<html>
<body>
<p>Click on button, elements from Array will remove</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<p id="removed"></p>
<script>
var fruits = ["Apple", "Orange", "Kiwi", "Cherry"];
document.getElementById("demo").innerHTML = fruits;
function myFunction() {
var popped = fruits.pop();
document.getElementById("demo").innerHTML = fruits;
document.getElementById("removed").innerHTML = popped;
}
</script>
</body>
</html>
Output: in GIF, every time removed the item to show. If no element remains in the array will show undefined.
How to Javascript array pop first
To remove the first element from JS Array, you have to use the shift() method.
let cats = ['Bob', 'Willy', 'Cati'];
cats.shift(); // ['Willy', 'Mini']
Do comment if you have any doubt and suggestion on this tutorial.
Note: The All JavaScript array pop method Examples are tested on Safari browser (Version 12.0.2).
OS: macOS 10.14 Mojave
Code: HTML 5 Version