W3cubDocs

/JavaScript

array.unshift

The unshift() method adds one or more elements to the beginning of an array and returns the new length of the array.

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

Browser compatibilityUpdate compatibility data on GitHub

Desktop
Chrome Edge Firefox Internet Explorer Opera Safari
Basic support 1 Yes 1 5.5 Yes Yes
Mobile
Android webview Chrome for Android Edge Mobile Firefox for Android Opera for Android iOS Safari Samsung Internet
Basic support Yes Yes Yes 4 Yes Yes Yes
Server
Node.js
Basic support Yes

See also

© 2005–2018 Mozilla Developer Network and individual contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/unshift