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

← All JS array methods · TypeScript vs JavaScript