JavaScript Reference ยท Array
Array.prototype.unshift()
Reference for JavaScript Array.prototype.unshift(): add one or more elements to the start of an array, change it in place and get the new length back.
The unshift() method adds one or more elements to the beginning of an array and returns the array's new length. It changes the array in place. It is the mirror image of push(), which adds to the end, and the partner of shift(), which removes from the start.
Because every existing element has to move to a higher index, unshift() is slower than push() on large arrays.
const queue = ["b", "c"]; const length = queue.unshift("a"); // queue is ["a", "b", "c"], length is 3
Try it
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Syntax
array.unshift() array.unshift(element1) array.unshift(element1, element2, /* โฆ, */ elementN)
| Name | Description |
|---|---|
element1, โฆ, elementN |
The elements to insert at the start of the array. They end up in the same order in which you pass them. |
Return value: the new length of the array. Calling unshift() with no arguments changes nothing and returns the current length.
Exceptions: TypeError if the new length would exceed 2^53 - 1, which does not happen with real arrays.
Usage notes
- It mutates. The array itself changes. The return value is a number, not the array, so
arr = arr.unshift(x)is a bug that replaces your array with a number. - One call keeps the order; several calls reverse it.
unshift("a", "b")yieldsa, b, ..., whileunshift("a")followed byunshift("b")yieldsb, a, .... - Arrays are inserted as single elements. To insert the items of another array, spread it:
arr.unshift(...other). Very long spreads can exceed the engine's argument limit. - Cost. All existing elements shift one place per inserted item, so the work grows with the array's length. A queue that mostly adds at the front can be slow; a different structure, or building in reverse and calling
reverse()once, may fit better. - Without mutation, write
[newItem, ...array]orarray.toSpliced(0, 0, newItem). - Generic. It works on array-likes through
Array.prototype.unshift.call(obj, ...), updatinglength. Frozen arrays throw aTypeError. - Holes in a sparse array stay holes, only shifted to new indexes.
Browser support
unshift() is a classic array method that works in every browser and Node.js version in use.