Array.prototype.unshift()
Baseline Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.
Theunshift() method ofArray instances adds the specified elements to thebeginning of an array and returns the new length of the array.
In this article
Try it
const array = [1, 2, 3];console.log(array.unshift(4, 5));// Expected output: 5console.log(array);// Expected output: Array [4, 5, 1, 2, 3]Syntax
unshift()unshift(element1)unshift(element1, element2)unshift(element1, element2, /* …, */ elementN)Parameters
element1, …,elementNThe elements to add to the front of the
arr.
Return value
The newlength property of the object upon which themethod was called.
Description
Theunshift() method inserts the given values to the beginning of anarray-like object.
Array.prototype.push() has similar behavior tounshift(), but applied to the end of an array.
Please note that, if multiple elements are passed as parameters, they're inserted inchunk at the beginning of the object, in the exact same order they were passed asparameters. Hence, callingunshift() withnargumentsonce, or calling itn times with1 argument (with a loop, for example), don't yield the same results.
See example:
let arr = [4, 5, 6];arr.unshift(1, 2, 3);console.log(arr);// [1, 2, 3, 4, 5, 6]arr = [4, 5, 6]; // resetting the arrayarr.unshift(1);arr.unshift(2);arr.unshift(3);console.log(arr);// [3, 2, 1, 4, 5, 6]Theunshift() method isgeneric. It only expects thethis value to have alength property and integer-keyed properties. Although strings are also array-like, this method is not suitable to be applied on them, as strings are immutable.
Examples
>Using unshift()
const arr = [1, 2];arr.unshift(0); // result of the call is 3, which is the new array length// arr is [0, 1, 2]arr.unshift(-2, -1); // the new array length is 5// arr is [-2, -1, 0, 1, 2]arr.unshift([-4, -3]); // the new array length is 6// arr is [[-4, -3], -2, -1, 0, 1, 2]arr.unshift([-7, -6], [-5]); // the new array length is 8// arr is [ [-7, -6], [-5], [-4, -3], -2, -1, 0, 1, 2 ]Calling unshift() on non-array objects
Theunshift() method reads thelength property ofthis. It shifts all indices in the range0 tolength - 1 right by the number of arguments (incrementing their values by this number). Then, it sets each index starting at0 with the arguments passed tounshift(). Finally, it sets thelength to the previous length plus the number of prepended elements.
const arrayLike = { length: 3, unrelated: "foo", 2: 4,};Array.prototype.unshift.call(arrayLike, 1, 2);console.log(arrayLike);// { '0': 1, '1': 2, '4': 4, length: 5, unrelated: 'foo' }const plainObj = {};// There's no length property, so the length is 0Array.prototype.unshift.call(plainObj, 1, 2);console.log(plainObj);// { '0': 1, '1': 2, length: 2 }Specifications
| Specification |
|---|
| ECMAScript® 2026 Language Specification> # sec-array.prototype.unshift> |