Array.prototype.unshift()
The unshift()
method adds one or more elements to the
beginning of an array and returns the new length of the array.
Syntax
unshift(element0)
unshift(element0, element1)
unshift(element0, element1, /* … ,*/ elementN)
Parameters
elementN
- : The elements to add to the front of the
arr
.
- : The elements to add to the front of the
Return value
The new Array.prototype.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.
Array.prototype.push()
has similar behavior to unshift()
, but applied to the end of an array.
Please note that, if multiple elements are passed as parameters, they're inserted in
chunk at the beginning of the object, in the exact same order they were passed as
parameters. Hence, calling unshift()
with n
arguments once, or calling it n
times with
1 argument (with a loop, for example), don't yield the same results.
See example:
let arr = [4, 5, 6];
arr.unshift(1, 2, 3);
console.log(arr);
// [1, 2, 3, 4, 5, 6]
arr = [4, 5, 6]; // resetting the array
arr.unshift(1);
arr.unshift(2);
arr.unshift(3);
console.log(arr);
// [3, 2, 1, 4, 5, 6]
The unshift()
method is generic. It only expects the this
value to have a length
property and integer-keyed properties. Although strings are also array-like, this method is not suitable to be applied on them, as strings are immutable.