Array.prototype.unshift()
Adds one or more elements to the beginning of an array and returns the new length.
Syntax
arr.unshift(...elements) Parameters
| Name | Type | Required | Description |
|---|---|---|---|
elements | any | No | One or more elements to prepend to the start of the array. |
Returns
number — The new length of the array.
Examples
const a = [3, 4];
const len = a.unshift(1, 2);
console.log(a, len);
Output
[ 1, 2, 3, 4 ] 4
const a = [2];
a.unshift(1);
console.log(a);
Output
[ 1, 2 ]
Notes
Mutates the array in place and re-indexes all existing elements (O(n)).
Multiple elements are inserted as a group in the given order.
Browser & runtime support
| Environment | Since version |
|---|---|
| chrome | 1.0 |
| firefox | 1.0 |
| safari | 1.0 |
| edge | 12 |
| node | 0.10 |