JavaScript(JS) JS add element to start of an array

You can add an element to the start of a JavaScript array using the unshift() method. Here's an example:

refer ‮igi:ot‬ftidea.com
let myArray = [1, 2, 3];
myArray.unshift(0);
console.log(myArray); // Output: [0, 1, 2, 3]

In the example above, we create an array myArray with three elements [1, 2, 3]. We then use the unshift() method to add the value 0 to the beginning of the array. The resulting array is [0, 1, 2, 3].

The unshift() method adds one or more elements to the beginning of an array and returns the new length of the array. If you want to add multiple elements to the beginning of an array, you can pass them as separate arguments to the unshift() method:

let myArray = [1, 2, 3];
myArray.unshift(0, -1, -2);
console.log(myArray); // Output: [-2, -1, 0, 1, 2, 3]

In the example above, we add three elements 0, -1, and -2 to the beginning of the array myArray. The resulting array is [-2, -1, 0, 1, 2, 3].