Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / JavaScript

Array.prototype.unshift: adding at the front

unshift shifts existing indexes right, inserts its arguments at the front, and returns the receiver’s new length.

Version: ECMAScript 1 onward; example target: Node.js 24.22.2

Syntax

array.unshift(...items)

array.unshift(...items) mutates array: it shifts existing indexed properties upward by the argument count, writes items starting at index zero, and updates length. It returns the new length, and arguments retain their order, so unshift("a", "b") places a before b. With no arguments, the length remains the same.

Holes are preserved while shifting: an absent source property causes the corresponding destination property to be deleted. The method is generic for mutable array-like objects and does not create a result array.

If the new length would exceed 2^53 - 1, it throws TypeError; ordinary Arrays have an additional length limit. Non-writable indexes or length, non-configurable properties, and failures from getters, setters, or proxy traps can interrupt the operation after partial changes. The API dates to ECMAScript 1.

Examples

const queue = ["test", "deploy"];
const length = queue.unshift("lint", "build");
console.log(length, queue.join(","));

const sparse = [, "b"];
const sparseLength = sparse.unshift("a");
console.log(sparseLength, 0 in sparse, 1 in sparse, 2 in sparse, sparse[0], sparse[2]);

const arrayLike = { 1: "second", length: 2 };
const result = Array.prototype.unshift.call(arrayLike, "first");
console.log(result, arrayLike.length, arrayLike[0], 1 in arrayLike, arrayLike[2]);

Result

4 lint,build,test,deploy
3 true false true a b
3 3 first false second

Sources