How the Array.unshift() method works in JavaScript ?
Last Updated :
30 Jan, 2024
The Array.unshift()
method in JavaScript is used to add one or more elements to the beginning of an array. It modifies the original array and returns the new length of the array after the elements have been added.
Key points about Array.unshift()
:
- It modifies the original array and returns the new length.
- It can accept multiple arguments, and each argument is added to the beginning of the array in the order specified.
- Elements are added in the same order as the arguments provided.
Example: Here, The unshift
method is called on the array myArray
. Two elements, 1
and 0
, are added to the beginning of the array. The modified array [1, 0, 2, 3, 4]
is logged to the console. The new length of the array, which is 5
after the addition of elements, is also logged.
Javascript
const myArray = [2, 3, 4];
const newLength = myArray.unshift(1, 0);
console.log(myArray);
console.log(newLength);
|
Output
[ 1, 0, 2, 3, 4 ]
5
Share your thoughts in the comments
Please Login to comment...