JavaScriptArrays

Array.prototype.shift()

Removes the first element of an array and returns it.

Returns
The removed first element, or undefined.
Changes the original
Yes
On this page

Example

#
JavaScript
const queue = ['Emma', 'Jack', 'Mia']
const next = queue.shift()

console.log(next)
console.log(queue)
Console
Emma
['Jack', 'Mia']

Definition and usage

#

The shift() method takes out the array’s first element, shifts the rest one position to the left, and returns the removed element. On an empty array it returns undefined.

Together with push(), it lets you use an array like a queue: the first item added comes out first, just like a checkout line.

Shifting every element costs time, so with very large arrays and frequent shift() calls, it can get slow.

Syntax

#
Syntax
array.shift()

Browser support

#

Widely available

Works in all modern browsers, phones included. You can use it without worry.

  • Chrome
  • Edge
  • Firefox
  • Safari

Good practices

#
  • To read the first element without removing it, array[0] is enough.
  • A non-mutating version: const rest = queue.slice(1) or const [first, ...rest] = queue.

Related entries

#

Spotted a mistake or missing an example? Write to us.