How to remove the last item from an array in JavaScript
Removing the last element from JavaScript arrays is essential when building stack-like data structures, managing dynamic content, or implementing undo functionality in user interfaces.
With over 25 years of experience in software development and as the creator of CoreUI, I have implemented this pattern countless times in components like pagination controls, breadcrumb navigation, and interactive forms where the last item needs to be removed.
From my extensive expertise, the most efficient and purpose-built solution is using the pop() method, which removes and returns the last element in a single operation.
This approach is optimized, intuitive, and designed specifically for this common use case.
Use the pop() method to remove and return the last item from an array.
const fruits = ['apple', 'banana', 'orange']
const lastFruit = fruits.pop()
// lastFruit: 'orange', fruits: ['apple', 'banana']
The pop() method modifies the original array by removing the last element and returns that removed element. In this example, fruits.pop() removes 'orange' from the end of the array and returns it, while the array becomes ['apple', 'banana']. The method returns the removed element, which you can capture in a variable if needed, or simply call fruits.pop() to discard the value.
1. Capturing the Removed Element
One of the key advantages of pop() is that it returns the element it removed. This is useful when you need to process the item, such as implementing an undo feature or displaying what was just deleted.
const history = ['/home', '/products', '/products/123', '/checkout']
const lastPage = history.pop()
console.log('Navigating back from:', lastPage)
// Result: 'Navigating back from: /checkout'
console.log('Current history:', history)
// Result: ['/home', '/products', '/products/123']
This pattern is the foundation of a stack data structure where items are processed in last-in, first-out (LIFO) order. In CoreUI breadcrumb components, we use this approach to implement back navigation by popping the most recent entry from the route history and redirecting the user to the previous page.
2. Handling Empty Arrays
When pop() is called on an empty array, it returns undefined rather than throwing an error. This makes it safe to call without checking the array length first, but you should handle the undefined return value if your logic depends on the removed item.
const emptyStack = []
const result = emptyStack.pop()
console.log(result)
// Result: undefined
console.log(emptyStack)
// Result: []
// Guard pattern for safe usage
const actionStack = []
const lastAction = actionStack.pop()
if (lastAction !== undefined) {
console.log('Undoing:', lastAction)
} else {
console.log('Nothing to undo')
}
// Result: 'Nothing to undo'
The undefined return value is a reliable signal that the array was already empty. This eliminates the need for a separate if (array.length > 0) check before calling pop(). However, if your array legitimately contains undefined as a value, you should check the length property instead to distinguish between an empty array and a removed undefined element.
3. Implementing an Undo Stack
A practical use of pop() is building an undo system where each action is pushed onto a stack and the most recent one can be reversed by popping it off.
const actions = []
// User performs actions
actions.push({ type: 'add', item: 'Header component' })
actions.push({ type: 'move', item: 'Sidebar', from: 'left', to: 'right' })
actions.push({ type: 'delete', item: 'Footer component' })
// User clicks undo
const lastAction = actions.pop()
console.log('Undoing:', lastAction.type, lastAction.item)
// Result: 'Undoing: delete Footer component'
console.log('Remaining actions:', actions.length)
// Result: 2
Each call to pop() removes the most recent action, allowing you to reverse operations in the correct order. This is the standard approach for implementing undo functionality in visual editors and drag-and-drop builders. In CoreUI dashboard builder tools, action stacks like this allow users to undo layout changes step by step.
4. Removing Multiple Items from the End
While pop() removes one element at a time, you can call it in a loop to remove a specific number of items from the end of an array.
const logs = ['[INFO] Start', '[DEBUG] Init', '[WARN] Slow', '[ERROR] Fail', '[INFO] Retry']
// Remove the last 2 log entries
const removed = []
for (let i = 0; i < 2; i++) {
removed.push(logs.pop())
}
console.log('Removed:', removed)
// Result: ['[INFO] Retry', '[ERROR] Fail']
console.log('Remaining:', logs)
// Result: ['[INFO] Start', '[DEBUG] Init', '[WARN] Slow']
Note that the removed items are in reverse order because pop() always takes from the end. If you need to remove multiple items from the end in a single operation, splice(-n) is more efficient: logs.splice(-2) removes and returns the last two elements in their original order.
5. Non-Mutating Alternative with slice()
In frameworks like React and Vue, state should not be mutated directly. Instead of pop(), use slice(0, -1) to create a new array without the last element, leaving the original untouched.
const colors = ['red', 'green', 'blue', 'yellow']
// Create a new array without the last item
const withoutLast = colors.slice(0, -1)
console.log(withoutLast)
// Result: ['red', 'green', 'blue']
// Original is unchanged
console.log(colors)
// Result: ['red', 'green', 'blue', 'yellow']
The slice(0, -1) call copies all elements from the start up to (but not including) the last one. The negative index -1 counts from the end of the array. This is the preferred approach in CoreUI React components where state immutability is required for proper change detection and re-rendering.
6. Combining pop() with push() for Rotation
You can combine pop() with other array methods to build useful patterns. A common one is rotating an array by moving the last element to the front.
const playlist = ['Song A', 'Song B', 'Song C', 'Song D']
// Rotate: move last item to the front
const lastSong = playlist.pop()
playlist.unshift(lastSong)
console.log(playlist)
// Result: ['Song D', 'Song A', 'Song B', 'Song C']
This reverse rotation pattern complements the forward rotation achieved with shift() and push(). Together, these two patterns give you full control over circular data structures like playlists, carousels, and round-robin schedulers without needing any additional libraries or complex index arithmetic.
Best Practice Note:
The pop() method mutates the original array in place, which is efficient for stack operations and imperative code. When immutability is required, such as in React or Vue state updates, use slice(0, -1) to create a new array without the last element. This is the same approach we use in CoreUI components to manage navigation history and dynamic content stacks. For related operations, see how to remove the first item, how to remove specific items, and how to get the last element.



