What is the pop() method in JavaScript, and how to use it to remove the last element from an array?
Discover how to manipulate arrays like a pro and boost your JavaScript skills with our definitive guide on the Array.pop() method.
Continue reading to elevate your coding journey!
What is pop()method in JavaScript?
The JavaScript array.pop() method is used to remove the last element from an array and also return that element.
This method changes the length of the array.
Here’s an example:
let subjects = ["Programming", "English", "Math"];
let lastElement = subjects.pop();✅
console.log(subjects);
console.log(lastElement);
console.log(subjects.length)In this example, the pop() method removes the last element, “Math,” from the subjects array.
The lastElement variable contains the returned value, “Math.”
You can also see that the length of the values of the subjects array decreases.
Output:
[ 'Programming', 'English' ] (subjects)
Math (last elements)
2 (subjects length)Syntax
arr.pop() ✅Parameters
NoneThe pop() method does not take any parameters.
Return value
This method returns the removed element from the array. If the array is empty, it will returned undefined.
Here’s an example:
let subjects = [];
let lastElement = subjects.pop();✅
console.log(lastElement);
console.log(subjects.length)Output:
undefined
0Supported Browser
✔ Chrome
✔ Edge
✔ Firefox
✔ Internet Explorer
✔ Safari Opera
Example Usage of pop method
// Let's say we have a list of tasks to do
let tasks = ["Do laundry", "Buy groceries", "Call mom", "Pay bills"];
console.log("Tasks to do: " + tasks);
// Now, we complete each task one by one, removing them from the list
while(tasks.length > 0) {
let currentTask = tasks.pop();
console.log("Doing task: " + currentTask);
console.log("Remaining tasks: " + tasks);
}
console.log("All tasks completed!");
The example code above, demonstrates how you can use the pop() method to manage and manipulate lists in JavaScript. Its a simple but powerful tool for array manipulation!
Here’s the illustration on how to use pop method:
- first declare a tasks array with four elements representing different tasks.
- Then use a while loop to keep popping and completing tasks until there are no more tasks left in the array.
- In each iteration of the loop, we use the pop() method to remove the last task from the tasks array and store it in the currentTask variable.
- Then log the current task and the remaining tasks to the console.
Once all tasks are completed (i.e., when the tasks array is empty), we log a completion message to the console.
Output:
Tasks to do: Do laundry,Buy groceries,Call mom,Pay bills
Doing task: Pay bills
Remaining tasks: Do laundry,Buy groceries,Call mom
Doing task: Call mom
Remaining tasks: Do laundry,Buy groceries
Doing task: Buy groceries
Remaining tasks: Do laundry
Doing task: Do laundry
Remaining tasks:
All tasks completed!Different scenarios where you might use the pop() method in JavaScript
Here are a few different scenarios where you might use the pop() method in JavaScript:
Scenario 1: Removing the last item from a shopping cart
let shoppingCart = ["LVBag", "Iphone", "NB Shoes"];
console.log("Shopping cart: " + shoppingCart);
let removedItem = shoppingCart.pop(); ✅
console.log("Removed item: " + removedItem);
console.log("Updated shopping cart: " + shoppingCart);Output:
Shopping cart: LVBag,Iphone,NB Shoes
Removed item: NB Shoes
Updated shopping cart: LVBag,IphoneScenario 2: Undo functionality in a text editor
let textHistory = ["It", "Welcome to Itsourcecode", "Hi, Welcome to Itsourcecode.com!"];
console.log("Text history: " + textHistory);
let undo = textHistory.pop(); ✅
console.log("Undo action, removed: " + undo);
console.log("Updated text history: " + textHistory);Output:
Text history: It,Welcome to Itsourcecode,Hi, Welcome to Itsourcecode.com!
Undo action, removed: Hi, Welcome to Itsourcecode.com!
Updated text history: It, Welcome to ItsourcecodeScenario 3: Backtracking in a browser history
let browserHistory = ["Home", "Search Results", "Itsourcecode.com"];
console.log("Browser history: " + browserHistory);
let back = browserHistory.pop(); ✅
console.log("Back action, removed: " + back);
console.log("Updated browser history: " + browserHistory);Browser history: Home, Search Results, Itsourcecode.com
Back action, removed: Itsourcecode.com
Updated browser history: Home, Search Resultspop() vs Related Array Removal Methods
| Method | Removes From | Returns | Performance |
|---|---|---|---|
pop() | End | Removed element | O(1) — fast |
shift() | Start | Removed element | O(n) — slow |
splice(i, 1) | Any position | Array of removed elements | O(n) |
filter() | By condition | New filtered array | O(n), does not mutate |
delete arr[i] | By index | true | Leaves sparse hole — AVOID |
Two important rules: never use delete arr[i] on an array (it leaves an empty slot, breaking length). And prefer pop() over shift() when you have a choice — shift requires re-indexing every remaining element, which is O(n) instead of O(1).
Using pop() to Build a Stack (LIFO)
JavaScript arrays naturally implement a Last-In-First-Out (LIFO) stack using push() and pop(). The classic undo/redo system uses exactly this pattern:
class EditorHistory {
constructor() {
this.undoStack = [];
this.redoStack = [];
}
save(state) {
this.undoStack.push(state);
this.redoStack = []; // new edit clears the redo history
}
undo() {
if (this.undoStack.length === 0) return null;
const state = this.undoStack.pop();
this.redoStack.push(state);
return state;
}
redo() {
if (this.redoStack.length === 0) return null;
const state = this.redoStack.pop();
this.undoStack.push(state);
return state;
}
}This 20-line class is the foundation of every undo/redo system in popular text editors. The pop() method is what makes it efficient.
pop() on an Empty Array
const empty = [];
const result = empty.pop();
console.log(result); // undefined
console.log(empty.length); // 0
// Common bug: not checking the return value
const next = empty.pop();
next.doSomething(); // ❌ TypeError on undefined
// Safe pattern:
if (empty.length > 0) {
const item = empty.pop();
// process item
}
// Or use optional chaining if processing:
empty.pop()?.doSomething();pop() returns undefined for empty arrays. Without a length check or optional chaining, your code will crash trying to access properties on undefined.
Common pop() Mistakes
- Forgetting that pop() MUTATES the array. Unlike
filter()orslice(), pop changes the original. If you need the array intact, clone first:const last = [...arr].pop(). - Expecting pop() to return the array. It returns the REMOVED element. If you chain like
arr.pop().anotherMethod(), you are operating on the removed element, not the array. - Using pop() inside
forEach(). Modifying the array during iteration causes undefined behavior — some elements get skipped or processed twice. Iterate over a copy or usewhile (arr.length). - Calling pop() on a frozen array.
Object.freeze(arr)makes pop throw TypeError in strict mode. Useful trick for preventing accidental mutation. - Confusing pop() with peek (no-op view). JavaScript has no built-in
peek()method. To look at the last element WITHOUT removing it, usearr[arr.length - 1]orarr.at(-1)(newer ES2022 syntax).
Conclusion
In conclusion, the pop() method in JavaScript serves to remove the last element from an array and also returns that element. This operation alters the length of the array.
You can utilize it as a straightforward yet effective tool for array manipulation. The method lacks parameters and, when applied to an empty array, it returns undefined.
We are hoping that this article provides you with enough information that helps you understand the array.pop in JavaScript.
Frequently Asked Questions
What does the pop() method do in JavaScript?
The pop() method removes the LAST element from an array and returns that element. It mutates the original array, decreasing its length by 1. For example, const arr = [1,2,3]; const x = arr.pop(); sets x to 3 and arr becomes [1, 2]. If the array is empty, pop() returns undefined and the array stays empty.
What’s the difference between pop() and shift() in JavaScript?
pop() removes from the END of the array. shift() removes from the START. pop() is much faster (O(1)) because it just decrements length. shift() is slower (O(n)) because every remaining element must be re-indexed. For implementing a queue (FIFO), shift() is needed; for a stack (LIFO), use pop().
Does pop() change the original array in JavaScript?
Yes — pop() MUTATES the original array. The array’s length decreases by 1 and the last element is removed. If you need the array unchanged, clone first with [...arr] or arr.slice() before calling pop(). Methods like filter() and slice() return new arrays without mutation.
What does pop() return if the array is empty?
It returns undefined. The array length stays at 0 and no error is thrown. This is a common bug source — calling a method on the return value crashes with TypeError. Always check arr.length > 0 first or use optional chaining: arr.pop()?.someMethod().
How do I get the last element without removing it?
Use array indexing or the newer at() method. arr[arr.length - 1] works in all browsers. arr.at(-1) is cleaner (ES2022, all modern browsers). Neither mutates the array. JavaScript has no built-in peek() method like other languages.
Related JavaScript Tutorials
- JavaScript Array find() Method
- Remove Empty Strings from Array
- Remove Commas from JavaScript String
- JavaScript Date Add Days
- JavaScript Tutorial Series
Thank you for reading Itsourcecoders 😊.
