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>
New on Educative
Learn any Language for FREE all September 🎉
For the entire month of September, get unlimited access to our entire catalog of beginner coding resources.
🎁 G i v e a w a y
30 Days of Code
Complete Educative’s daily coding challenge every day in September, and win exciting Prizes.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved