The pop() method in JavaScript is used to remove the last element from an array and return that element. It modifies the original array by reducing its length by one.
- It returns the removed element.
- If the array is empty, it returns
undefined. - It modifies the original array (does not create a new one).
- The method does not accept any parameters.
- It reduces the array length by one after execution.
- Commonly used in stack implementations (LIFO-Last In, First Out).
let a = [1,2,3,4];
console.log(a);
// Remove the last element using pop()
let b = a.pop();
console.log("Removed string from array: ", a);
Output
[ 'Apple', 'Banana', 'Mango', 'Orange' ] removed string from array: Orange
Syntax:
arr.pop();1. pop() on an Empty Array
let a = [];
let b = a.pop();
console.log(b);
console.log(a);
Output
undefined []
The array is empty, there’s no element to remove, and the method returns undefined.
2. pop() in a Stack Implementation
The pop() method is often used in stack data structures to remove the top element (LIFO-Last In, First Out).
// Create an empty array to use as a stack
let a = [];
// Push elements into the stack
a.push(10);
a.push(20);
a.push(30);
// Remove (pop) the last element added — follows LIFO (Last In, First Out)
console.log(a.pop());
// Remove the next last element
console.log(a.pop());
// Display the remaining elements in the stack
console.log(a);
Output
30 20 [ 10 ]
Each call to pop() removes the last pushed element, just like removing items from a stack.