JavaScript Reference ยท Array
Array.prototype.pop()
Reference for JavaScript Array.prototype.pop(): remove and return the last element, how it changes length, behavior on empty arrays and stack usage.
The pop() method removes the last element from an array and returns it. The array becomes one element shorter. On an empty array it does nothing and returns undefined.
Together with push(), it turns an array into a stack: last in, first out. It is fast because it touches only the end of the array.
const stack = [1, 2, 3]; stack.pop(); // 3 // stack is now [1, 2]
Try it
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Syntax
array.pop()
Parameters: none.
Return value: the removed element, or undefined if the array was empty.
Exceptions: a TypeError if the array is frozen or the length cannot be changed (for example Object.freeze([1]).pop()).
Usage notes
- It mutates. The original array loses its last element. To get a copy without it, use
slice(0, -1). - Ambiguous
undefined. If the array can holdundefinedvalues, a result ofundefineddoes not tell you whether the array was empty. Checklengthfirst if that matters. - Peek without removing: use
array.at(-1). - Stack and queue.
push()andpop()implement a stack. For a queue, pairpush()withshift(). - Sparse arrays: popping a hole at the end returns
undefinedand still reduces the length. - Generic. It works on array-likes that have a writable
length, throughArray.prototype.pop.call(...). - Frozen arrays throw; arrays that are merely
constdo not, becauseconstprotects the binding, not the contents. - Performance: removing from the end is cheap; removing from the start (
shift()) can be slower on very large arrays.
Browser support
Array.prototype.pop() is part of ES3 and works everywhere.