**pop()** removes the last element and returns it. It mutates the array. Together with **push()**, it implements a **stack** (LIFO — Last In, First Out). For a queue (FIFO), use **push()** and **shift()**.
1Understanding Array.pop()
pop() removes the last element and returns it. It mutates the array. Together with push(), it implements a stack (LIFO — Last In, First Out). For a queue (FIFO), use push() and shift().
pop() on an empty array returns undefined without throwing an error.
// Stack implementation with push/pop
const history = [];
function navigate(url) { history.push(url); }
function goBack() { return history.pop(); }
navigate('/home');
navigate('/about');
navigate('/contact');
console.log(history); // ['/home', '/about', '/contact']
console.log(goBack()); // '/contact'
console.log(history); // ['/home', '/about']2Practical Example
Here is a real-world application of Array.pop() showing how it is used in production JavaScript code.
// Non-mutating last removal
const arr = [1, 2, 3, 4, 5];
const withoutLast = arr.slice(0, -1);
console.log(arr); // [1,2,3,4,5] unchanged
console.log(withoutLast); // [1,2,3,4]3Best Practices
Follow these guidelines when working with Array.pop():
1. Use push()/pop() to implement stacks
2. Check array.length before popping if empty arrays are possible
3. Use slice(0, -1) for non-mutating removal of last element
Tip: pop() on an empty array returns undefined without throwing an error.
// Stack implementation with push/pop
const history = [];
function navigate(url) { history.push(url); }
function goBack() { return history.pop(); }
navigate('/home');
navigate('/about');
navigate('/contact');
console.log(history); // ['/home', '/about', '/contact']
console.log(goBack()); // '/contact'
console.log(history); // ['/home', '/about']