Home >>JavaScript Array Reference >JavaScript Array unshift() Method

JavaScript Array unshift() Method

JavaScript Array unshift() Method

JavaScript unshift() method is used to add new items to the beginning of the given input array and return the new length. It changes the length of the given array.

Syntax:
array.unshift(item1, item2, ..., itemX)

Parameter Values

Parameter Description
item1, item2, ..., itemX This is a required parameter. It defines the items to add to the beginning of the array.

Browser Support

Method Chrome Edge Firefox Safari Opera
unshift() 1.0 5.5 1.0 Yes Yes
Here is an example of JavaScript unshift() method:
<html>
<body>
<p>Click the button to see the Output.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
var x = ["A", "B", "C", "D", "E"];
document.getElementById("demo").innerHTML = x;
function myFunction() 
{
  x.unshift("x", "x");
  document.getElementById("demo").innerHTML = x;
}
</script>
</body>
</html>
Output:

Click the button to see the Output.

Example 2:
<html>
<body>
<p>Click the button to see the Output.</p>
<button onclick="myFunction1()">Try it</button>
<p id="demo1"></p>
<script>
var x = [0, 1, 2, 3, 4, 5, 6, 7];
document.getElementById("demo1").innerHTML = x;
function myFunction1() 
{
  x.unshift("x");
  document.getElementById("demo1").innerHTML = x;
}
</script>
</body>
</html>
Output:

Click the button to see the Output.