The JavaScript array.pop() method
The pop() method removes the last element from an array and returns it, shortening the array by one. const a = [1, 2, 3]; a.pop() returns 3 and leaves a as [1, 2]. On an empty array it returns undefined. Together with push() it gives you a stack.
Overview
pop() takes the last element off an array and hands it to you, while removing it from the array. It's the natural partner to push(): push adds to the end, pop takes from the end. That pairing is exactly a stack — last in, first out — which shows up in undo history, navigation, and plenty of algorithms.
Like push, it mutates the array in place and the array gets one shorter. If you call it on an empty array, there's nothing to remove, so it returns undefined and the array stays empty — no error. The returned value is the element itself, so you can use it right away.
To remove from the start instead, use shift(). To remove from somewhere in the middle, use splice(). If you need the last element without removing it, just read arr[arr.length - 1] (or arr.at(-1)).
Syntax
const lastElement = array.pop()
Example
<pre id="out" style="font:15px ui-monospace,monospace"></pre>
<script>
const history = ['home', 'about', 'contact'];
const last = history.pop();
document.getElementById('out').textContent =
'removed: ' + last + '\n' +
'left: ' + history.join(', '); // removed: contact / left: home, about
</script>
Best practices
- Use the return value —
pop()gives you the removed element, so capture it if you need it. - Guard against the empty case if it matters: on
[]it returnsundefined. - Pair
pop()with push() for stack (last-in, first-out) behavior. - To peek at the last item without removing it, read
arr.at(-1)instead of popping.
Frequently asked questions
What does pop() return in JavaScript?
undefined.Does pop() change the original array?
How do I remove the first element instead of the last?
shift(), which removes and returns the first element. Its counterpart unshift() adds to the front.How do I get the last element without removing it?
arr[arr.length - 1] or the cleaner arr.at(-1).