The shift() Method

Elements in an array can be shifted around. Shifting is equivalent to popping, working on the first element instead of the last. The shift(1st-element) method removes the first element of an array, and "shifts" all other elements one place up. Using shift() returns the string that was "shifted out":

HTML file: Displayed by browser:
<body>
<h4>The original, untouched array:</h4>
<p id="demo"></p>
<hr />
<h4>The shift method removes the first element from the beginning of an array:</h4>
<button onclick="myShift()">Shift it Out</button>
<p id="demo1"></p>
<hr />
<h4>The element that has been removed:</h4>
<button onclick="myRemoved()">What was Removed?</button>
<p id="demo2"></p>
<script>
var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits;
var x = fruits.shift();
fruits.unshift(x);
function myShift() {
    fruits.shift();
    document.getElementById("demo1").innerHTML = fruits;
}
function myRemoved() {
    document.getElementById("demo2").innerHTML = x;
}
</script>
</body>

The original, untouched array:


The shift method removes the first element from the beginning of an array:


The element that has been removed:


BackTable of ContentsNext