Codectionary / Developer documentation / JavaScript

push(), pop(), shift(), unshift()

These four methods add or remove elements from the ends of an array, all mutating the original array in place. push() and pop() work on the end of the array (fast). shift() and unshift() work on the beginning (slower, since remaining elements must be re-indexed).

Syntax

arr.push(item); arr.pop();
arr.unshift(item); arr.shift();

Examples

push() and pop() - End of Array

Adding and removing elements from the end.

const stack = [1, 2, 3];

stack.push(4);        // adds to the end
console.log(stack);   // [1, 2, 3, 4]

const removed = stack.pop(); // removes and returns the last element
console.log(removed);  // 4
console.log(stack);    // [1, 2, 3]

unshift() and shift() - Start of Array

Adding and removing elements from the beginning.

const queue = [2, 3, 4];

queue.unshift(1);     // adds to the start
console.log(queue);   // [1, 2, 3, 4]

const first = queue.shift(); // removes and returns the first element
console.log(first);    // 1
console.log(queue);    // [2, 3, 4]

Adding Multiple Elements at Once

Each method accepts multiple arguments.

const arr = [3];
arr.push(4, 5, 6);
console.log(arr); // [3, 4, 5, 6]

arr.unshift(1, 2);
console.log(arr); // [1, 2, 3, 4, 5, 6]

Best practices

  • Prefer push()/pop() over unshift()/shift() when performance matters - operating on the end of an array is significantly faster
  • Remember all four methods mutate the original array - use spread syntax ([...arr, newItem]) instead if you need an immutable update
  • Use push() to build up an array in a loop rather than repeatedly using concat(), which creates a new array each time
  • Check array length before calling pop()/shift() on a potentially empty array, since they return undefined rather than throwing

At a glance

Purpose
Application logic and interaction
File extension
.js ยท .mjs
Runs in
Browsers and JavaScript runtimes
Usually used with
HTML, CSS and Web APIs

Specifications & further reading

Related JavaScript documentation