Open In App

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

Last Updated : 30 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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




// 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

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads