JavaScript unshift() Method
The unshift()
method is a built-in function in JavaScript that adds one or more elements to the beginning of an array and returns the new length of the array.
Syntax
The syntax for unshift()
is:
array.unshift(element1, element2, ..., elementN)
Where array
is the array on which the unshift()
method is called, element1
to elementN
are the elements that you want to add to the beginning of the array.
Example
Consider the following example of the unshift()
method:
let fruits = ["banana", "orange", "apple"];
let length = fruits.unshift("grapes", "kiwi");
console.log("New array: " + fruits);
console.log("New length: " + length);
Output
The output of the above example will be:
New array: ["grapes", "kiwi", "banana", "orange", "apple"]
New length: 5