mutation
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.
arr.unshift(...elements) Parameters
| Parameter | Purpose |
|---|---|
| ...elements | One or more values to prepend (variadic) |
| return value | The array's new length after prepending |
Examples
const a = [3, 4]; a.unshift(1, 2); console.log(a); Logs: [1, 2, 3, 4]
const a = [2, 3]; console.log(a.unshift(1)); Logs: 3 (returns new length)
const a = [3]; a.unshift(1, 2); console.log(a); Logs: [1, 2, 3] (arguments preserve their order)
const a = [1]; a.unshift([0]); console.log(a); Logs: [[0], 1] (use spread to prepend an array's contents)
Gotcha
MUTATES the source, returns the new LENGTH, and is O(n) due to reindexing. Multi-arg calls preserve argument order at the front.
Related methods
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.
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.
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.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.