Skip to content
Tutorials Center
My learning

Topics

JavaScript Reference ยท Array

Array.prototype.shift()

Reference for JavaScript Array.prototype.shift(): remove and return the first element, how indexes move down, using it as a queue and its cost on big arrays.

The shift() method removes the first element of an array and returns it. All remaining elements move one position toward the start, so the old element at index 1 is now at index 0, and the array is one element shorter. On an empty array it returns undefined.

Paired with push(), it gives you a queue: first in, first out.

JavaScript
const queue = ["a", "b", "c"];
queue.shift(); // "a"
// queue is now ["b", "c"]

Try it

JS Taking from the front

Press Run (or Ctrl + Enter) to see the console output here.

No output.

JS A simple job queue

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Syntax

JavaScript
array.shift()

Parameters: none.

Return value: the removed first element, or undefined if the array was empty.

Exceptions: a TypeError if the array is frozen.

Usage notes

  • It mutates. To get the rest of an array without changing it, use slice(1) or destructuring: const [first, ...rest] = array.
  • Indexes shift. Because everything moves down, calling shift() inside a forEach() or an index-based loop skips elements. Use a while (array.length) loop instead.
  • Cost. Moving every element makes shift() slower than pop() on very large arrays, although engines optimize common cases. If you process millions of queued items, consider an index pointer or a linked structure.
  • Ambiguous undefined. If the array can contain undefined, check length to tell "empty" from "removed an undefined".
  • Queue and stack. push() + shift() is a queue; push() + pop() is a stack.
  • The opposite is unshift(), which adds to the front.
  • Peek without removing: array[0] or array.at(0).
  • Generic. It also works on array-likes with Array.prototype.shift.call(obj); for example, arguments can be consumed this way.

Browser support

Array.prototype.shift() is part of ES3 and works everywhere.