Array.prototype.unshift
Adds elements to the beginning of an array.
Available since: ES3
Syntax
array.unshift(element1, element2, /* … */)Parameters
| Parameter | Type | Description |
|---|---|---|
| element1, … | any | Elements to add to the beginning. |
Return value
numberThe new length of the array.
Examples
Adding to the beginning:
const list = ['b', 'c'];
list.unshift('a');
console.log(list);Output:
[
"a",
"b",
"c"
]The method returns the new length, not the array:
const list = ['c'];
console.log(list.unshift('a', 'b'));
console.log(list.join(''));Output:
3
abcNotes
The method changes the array itself. To get a new array and keep the old one, use spread: ['a', ...list].
See also
- Array.prototype.shift — Removes the first element of an array and returns it.
- Array.prototype.push — Appends elements to the end of an array.
Related recipes
In the tutorial
- Arrays — What an array is in JavaScript: creating one, indexes, length, changing elements and nested arrays.