What does pop() do?
The pop() method in JavaScript is the "opposite sibling" of push().
It removes the last element of the array and returns its value.
Example:
javascript
const fruits = ["apple", "banana", "cherry"];
const last = fruits.pop();
console.log(last); // "cherry", the removed element
console.log(fruits); // ["apple", "banana"]pop()mutates the original array.- It returns the removed element, not the length.
- If the array is empty, it returns
undefined.
Example with an empty array:
javascript
const arr = [];
const removed = arr.pop();
console.log(removed); // undefined
console.log(arr); // []How it works:
- Removes the element at index
length - 1. - Decreases
lengthby 1. - Returns the value of that element.
Comparison with push()
| Method | What it does | Returns | Changes the array |
|---|---|---|---|
push() | Adds to the end | The new length | Yes |
pop() | Removes from the end | The removed element | Yes |
Example of using them together:
javascript
const stack = [];
stack.push("a");
stack.push("b");
stack.push("c");
console.log(stack); // ["a", "b", "c"]
console.log(stack.pop()); // "c"
console.log(stack.pop()); // "b"
console.log(stack); // ["a"]push() and pop() are often used together to implement a stack: a "last in, first out" (LIFO) data structure.
In short:
| Action | Description |
|---|---|
arr.pop() | Removes the last element |
| Returns | The removed element |
| Changes the array | Yes |
| On an empty array | Returns undefined |
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.