Adding an element at the start of the array in Javascript

JavascriptWeb DevelopmentFront End Technology

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"]
raja
Published on 26-Jun-2018 17:05:04
Advertisements