The JavaScript array.shift() method
The shift() method removes the first element from an array and returns it, moving every other element down one index. const a = [1, 2, 3]; a.shift() returns 1 and leaves a as [2, 3]. It's the front-of-the-array counterpart to pop(), and together with unshift() it builds a queue.
Overview
shift() takes the first element off an array and hands it to you, while the array shrinks by one. It's the mirror of pop() (which removes from the end): shift works at the front. Pair shift() with push() and you have a queue — add to the back, remove from the front, first in first out.
Like the other front/back mutators, it changes the array in place and returns the removed element. On an empty array there's nothing to remove, so it returns undefined without throwing. Its opposite number for adding to the front is unshift().
One performance note worth knowing: because shift() has to re-index every remaining element (everything moves down a slot), it's O(n), unlike pop() which is O(1). For small arrays this never matters, but for a heavily used queue with huge arrays, a different data structure can be faster.
Syntax
const first = array.shift()
const q = ["a", "b", "c"];
q.shift(); // returns "a", q is now ["b", "c"]
Example
<pre id="out" style="font:15px ui-monospace,monospace"></pre>
<script>
const queue = ['first', 'second', 'third'];
const next = queue.shift();
document.getElementById('out').textContent =
'served: ' + next + '\n' +
'waiting: ' + queue.join(', '); // served: first / waiting: second, third
</script>
Best practices
- Capture the return value —
shift()gives you the element it removed. - Pair it with push() for a first-in-first-out queue.
- Use
unshift()to add to the front;shift()only removes. - For very large, hot queues, remember
shift()is O(n) — consider another structure if it shows up in profiling.
Frequently asked questions
What does shift() do in JavaScript?
What is the difference between shift() and pop()?
shift() removes the first element; pop() removes the last. Both mutate the array and return the removed item.How do I add to the front of an array?
unshift(), the counterpart to shift(). It adds one or more elements to the start and returns the new length.