Open In App

How the Array.unshift() method works in JavaScript ?

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():



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.




// Original array
const myArray = [2, 3, 4];
 
// Using unshift to add elements to the beginning
const newLength = myArray.unshift(1, 0);
 
console.log(myArray);
// Output: [1, 0, 2, 3, 4]
 
console.log(newLength);
// Output: 5

Output

[ 1, 0, 2, 3, 4 ]
5
Article Tags :