JavaScriptArrays
Array. prototype. pop()
Removes the last element of an array and returns it.
- Returns
- The removed element, or
undefinedfor an empty array. - Changes the original
- Yes
Example
#JavaScript
const history = ['step 1', 'step 2', 'step 3']
const undone = history.pop()
console.log(undone)
console.log(history)
console.log([].pop())Console
step 3
['step 1', 'step 2']
undefined
Definition and usage
#The pop() method takes out the array’s last element, shortens it by one, and returns the removed element. On an empty array it returns undefined.
Together with push(), it lets you use an array like a stack: the last item added comes out first. That’s how, for example, an undo history works.
The method changes the original array. If you need an array without its last element, but without mutation, use slice(0, -1).
Syntax
#Syntax
array.pop()Browser support
#Widely available
Works in all modern browsers, phones included. You can use it without worry.
- Chrome
- Edge
- Firefox
- Safari
Good practices
#- To read the last element without removing it, use
at(-1). - A non-mutating version:
const rest = history.slice(0, -1).
Related entries
#- Array.prototype.push()Adds elements to the end of an array and returns its new length.
- Array.prototype.shift()Removes the first element of an array and returns it.
- Array.prototype.at()Returns the element at the given index, which can also be counted from the end.
- Array.prototype.slice()Returns a copy of part of an array without changing the original.
Spotted a mistake or missing an example? Write to us.