0
0
JavascriptHow-ToBeginner · 3 min read

How to Use Push and Pop in JavaScript Arrays

In JavaScript, use push() to add one or more elements to the end of an array, and pop() to remove the last element from the array. Both methods modify the original array and pop() returns the removed element.
📐

Syntax

push() adds elements to the end of an array and returns the new length of the array.

pop() removes the last element from an array and returns that element.

javascript
array.push(element1, element2, ...);
const removedElement = array.pop();
💻

Example

This example shows how to add items to an array using push() and remove the last item using pop(). It also logs the array and removed element to the console.

javascript
const fruits = ['apple', 'banana'];

// Add 'orange' and 'grape' to the end
fruits.push('orange', 'grape');
console.log(fruits); // ['apple', 'banana', 'orange', 'grape']

// Remove the last element
const lastFruit = fruits.pop();
console.log(lastFruit); // 'grape'
console.log(fruits); // ['apple', 'banana', 'orange']
Output
['apple', 'banana', 'orange', 'grape'] grape ['apple', 'banana', 'orange']
⚠️

Common Pitfalls

  • Using pop() on an empty array returns undefined, so check array length if needed.
  • Both push() and pop() change the original array, which might cause bugs if you expect immutability.
  • Remember push() can add multiple elements at once, but pop() only removes one element.
javascript
const arr = [];

// Wrong: expecting pop to throw error or return something else
const removed = arr.pop();
console.log(removed); // undefined

// Right: check if array is empty before popping
if (arr.length > 0) {
  arr.pop();
} else {
  console.log('Array is empty');
}
Output
undefined Array is empty
📊

Quick Reference

MethodPurposeReturnsModifies Original Array
push(element1, ...)Add elements to endNew length of arrayYes
pop()Remove last elementRemoved element or undefined if emptyYes

Key Takeaways

Use push() to add one or more elements to the end of an array.
Use pop() to remove and get the last element from an array.
Both methods change the original array directly.
pop() returns undefined if the array is empty, so check length if needed.
push() can add multiple elements at once, pop() removes only one.