What is the unshift() method?

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.

Syntax

array.unshift(item1, item2,...)

Code

<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 chocolates
var choc = ["Hersheys", "Kitkat", "Snickers"];
document.getElementById("demo").innerHTML = choc;
function myfunc() {
// the function adds these chocolate names to the start of array
x = choc.unshift("Twix", "Mars");
document.getElementById("demo").innerHTML = choc;
document.getElementById("demo1").innerHTML = x;
}
</script>

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved