mutation
Array.prototype.shift
Removes the first element from the array and returns it, reindexing every remaining element. Reach for it to consume the head of a list — the natural queue operation.
arr.shift() Parameters
| Parameter | Purpose |
|---|---|
| (no parameters) | Takes no arguments |
| return value | The removed element, or undefined if the array was empty |
Examples
const a = [1, 2, 3]; console.log(a.shift()); Logs: 1
const a = [1, 2, 3]; a.shift(); console.log(a); Logs: [2, 3]
console.log([].shift()); Logs: undefined
const q = ['a','b','c']; while (q.length) console.log(q.shift()); Logs: 'a', 'b', 'c' (FIFO drain)
Gotcha
MUTATES the source and is O(n) because every remaining element must be reindexed — avoid in hot loops for large arrays.
Related methods
Array.prototype.unshift
Prepends one or more elements to the front of the array and returns the new length. Reach for it to insert at the head — but be aware every existing item is reindexed.
Array.prototype.pop
Removes the last element from the array and returns it (or undefined if empty). Reach for it to consume the tail of a list — the natural pair to push for stack behavior.
Array.prototype.splice
Removes and/or inserts elements at any position in the array, returning the removed items. Reach for it to do insert/delete/replace edits in one call.
Array.prototype.push
Appends one or more elements to the end of the array and returns the new length. Reach for it to grow a list — it's the canonical "add to the end" call.