The unshift() Method

Like the push() method (which adds a new element to the end of an array), the unshift(element) method adds a new element at the beginning of an array and "unshifts" older elements. Also, like the push() method, the unshift() method returns the new array length (the number of items in the array):

HTML file: Displayed by browser:
<body>
<h4>The original, untouched array:</h4>
<p id="demo"></p>
<hr />
<h4>The unshift method appends a new element at the beginning of an array:</h4>
<button onclick="myUnshift()">Unshift it In</button>
<p id="demo1"></p>
<hr />
<h4>The unshift method returns the number of items in the array:</h4>
<button onclick="myCount()">How Many Items?</button>
<p id="demo2"></p>
<script>
var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits;
function myUnshift() {
    fruits.unshift("Lemon");   // Adds lemon to fruits
    document.getElementById("demo1").innerHTML = fruits;
}
function myCount() {
    document.getElementById("demo2").innerHTML = fruits.unshift();
}
</script>
</body>

The original, untouched array:


The unshift method appends a new element at the beginning of an array:


The unshift method returns the number of items in the array:


BackTable of ContentsNext