In JavaScript, you can use the unshift() method to add an element to the beginning of an array. The unshift() method adds one or more elements to the beginning of an array and returns the new length of the array.

For example:

let fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.unshift("Lemon");
console.log(fruits); 

This will add “Lemon” to the beginning of the fruits array and the output will be [“Lemon”, “Banana”, “Orange”, “Apple”, “Mango”].

You can also use the spread operator to add an element to the beginning of an array.

let fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits = ["Lemon", ...fruits];
console.log(fruits);

This will also add “Lemon” to the beginning of the fruits array and the output will be [“Lemon”, “Banana”, “Orange”, “Apple”, “Mango”].

Also Read:

Categorized in: