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 to Code
Learn any Language as a beginner
Develop a human edge in an AI powered world and learn to code with AI from our beginner friendly catalog
🏆 Leaderboard
Daily Coding Challenge
Solve a new coding challenge every day and climb the leaderboard

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved