What is the use of the unshift() method in JavaScript?

The unshift() method in JavaScript is used to add one or more elements to the beginning of an array and returns the new length of the array.

Syntax of the unshift() method:

Here is syntax of the unshift() method

array.unshift(element1[, element2[, ...[, elementN]]])

The unshift() method takes one or more elements as arguments and inserts them at the beginning of the array. The first element passed to unshift() becomes the first element in the array, followed by the existing elements.

For example:

let myArray = [3, 4, 5];
myArray.unshift(1, 2); // adds elements 1 and 2 to the beginning of the array
console.log(myArray); // output: [1, 2, 3, 4, 5]

In this example, the unshift() method is used to add the elements 1 and 2 to the beginning of the myArray array. The output of console.log(myArray) shows that the array now contains the elements [1, 2, 3, 4, 5].

Thank you for reading, and let’s have conversation with each other

Thank you for reading my article. Let’s have conversation on Twitter and LinkedIn by connecting.

Read more: