Open In App

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

In JavaScript, the Array.unshift() method is used to add one or more elements to the beginning of an array. It modifies the original array by adding the specified elements at the front, shifting existing elements to higher indices to accommodate the new elements.

Syntax:

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

Example: Here, we have an array initially containing [3, 4, 5]. The unshift() method adds the elements 1 and 2 to the beginning of the array, resulting in [1, 2, 3, 4, 5]




const array = [3, 4, 5];
 // Adds 1 and 2 to the beginning of the array
array.unshift(1, 2);
console.log(array);

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