Skip to main content

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 length by 1.
  • Returns the value of that element.

Comparison with push()

MethodWhat it doesReturnsChanges the array
push()Adds to the endThe new lengthYes
pop()Removes from the endThe removed elementYes

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:

ActionDescription
arr.pop()Removes the last element
ReturnsThe removed element
Changes the arrayYes
On an empty arrayReturns undefined

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.