The unshift()
method adds one or more elements to the beginning of an array and returns the new length of the array.
var a = [1, 2, 3]; a.unshift(4, 5); console.log(a); // [4, 5, 1, 2, 3]
Syntax
arr.unshift([element1[, ...[, elementN]]])
Parameters
elementN
- The elements to add to the front of the array.
Return value
The new length
property of the object upon which the method was called.
Description
The unshift
method inserts the given values to the beginning of an array-like object.
unshift
is intentionally generic; this method can be called or applied to objects resembling arrays. Objects which do not contain a length
property reflecting the last in a series of consecutive, zero-based numerical properties may not behave in any meaningful manner.
Examples
var arr = [1, 2]; arr.unshift(0); // result of call is 3, the new array length // arr is [0, 1, 2] arr.unshift(-2, -1); // = 5 // arr is [-2, -1, 0, 1, 2] arr.unshift([-3]); // arr is [[-3], -2, -1, 0, 1, 2]
Specifications
Specification | Status | Comment |
---|---|---|
ECMAScript 3rd Edition (ECMA-262) | Standard | Initial definition. Implemented in JavaScript 1.2. |
ECMAScript 5.1 (ECMA-262) The definition of 'Array.prototype.unshift' in that specification. |
Standard | |
ECMAScript 2015 (6th Edition, ECMA-262) The definition of 'Array.prototype.unshift' in that specification. |
Standard | |
ECMAScript Latest Draft (ECMA-262) The definition of 'Array.prototype.unshift' in that specification. |
Living Standard |
Browser compatibility
Feature | Chrome | Edge | Firefox (Gecko) | Internet Explorer | Opera | Safari |
---|---|---|---|---|---|---|
Basic support | 1.0 | (Yes) | 1.0 (1.7 or earlier) | 5.5 | (Yes) | (Yes) |
Feature | Android | Chrome for Android | Edge | Firefox Mobile (Gecko) | IE Mobile | Opera Mobile | Safari Mobile |
---|---|---|---|---|---|---|---|
Basic support | (Yes) | (Yes) | (Yes) | (Yes) | (Yes) | (Yes) | (Yes) |
See also
Document Tags and Contributors
Tags:
Contributors to this page:
erikadoyle,
kaiyoma,
oksana-khristenko,
techmexdev,
bakotaco,
fscholz,
eduardoboucas,
Mingun,
denim2x,
netinept,
Sheppy,
ethertank,
zirak,
Anuarbek Safiyev,
evilpie,
Brettz9,
Sevenspade,
Mgjbot,
Yuichirou,
Maian,
Dria
Last updated by:
erikadoyle,