Computer >> Computer tutorials >  >> Programming >> Javascript

Adding an element at the start of the array in Javascript


This can be accomplished using the unshift method. For example,

let veggies = ["Onion", "Raddish"];
veggies.unshift("Cabbage");
console.log(veggies);

This will give the output.

["Cabbage", "Onion", "Raddish"]

You can also use this to unshift multiple items at the same time as it supports a variable number of arguments. For example −

let veggies = ["Onion", "Raddish"];
veggies.unshift("Cabbage", "Carrot", "Broccoli");
console.log(veggies);

This will give the output.

["Cabbage", "Carrot", "Broccoli", "Onion", "Raddish"]