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.
const queue = ["a", "b", "c"]; queue.shift(); // "a" // queue is now ["b", "c"]
Try it
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Syntax
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 aforEach()or an index-based loop skips elements. Use awhile (array.length)loop instead. - Cost. Moving every element makes
shift()slower thanpop()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 containundefined, checklengthto 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]orarray.at(0). - Generic. It also works on array-likes with
Array.prototype.shift.call(obj); for example,argumentscan be consumed this way.
Browser support
Array.prototype.shift() is part of ES3 and works everywhere.