The unshift()
method adds new items to the beginning of an array. This method changes the length of the array and returns the new length of the array.
array.unshift(item1, item2,...)
<p>Clicking on the button will add items to start of array.</p><button onclick="myfunc()">Click</button><p id="demo"></p><p id="demo1"></p><script>// given an array of chocolatesvar choc = ["Hersheys", "Kitkat", "Snickers"];document.getElementById("demo").innerHTML = choc;function myfunc() {// the function adds these chocolate names to the start of arrayx = choc.unshift("Twix", "Mars");document.getElementById("demo").innerHTML = choc;document.getElementById("demo1").innerHTML = x;}</script>
Free Resources