The pop() Method

When you work with arrays, it is easy to remove elements and add new elements. This is what "popping" and "pushing" is: Popping items out of an array, or pushing items into an array. The pop() method removes the last element from an array. Using "array-name.pop()" returns the value (variable x) that was "popped out":

HTML file: Displayed by browser:
<body>
<h4>The original, untouched array:</h4>
<p id="demo"></p>
<hr />
<h4>The pop method removes the last element from an array:</h4>
<button onclick="myPopping()">Pop it Out</button>
<p id="demo1"></p>
<hr />
<h4>The pop method returns the removed item:</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.pop();
fruits.push(x);
function myPopping() {
    fruits.pop();
    document.getElementById("demo1").innerHTML = fruits;
    fruits.push(x);
}
function myRemoved() {
    document.getElementById("demo2").innerHTML = x;
}
</script>
</body>

The original, untouched array:


The pop method removes the last element from an array:


The pop method returns the removed item:

Note to myself: Spent two hours composing this really tricky code! I had to push Mango back into the array and just at the right location in the script. Otherwise, Mango was not on the original array and I was popping Apple out, even though the value of x was always Mango. It was all just too weird, just like programming can be sometimes, but it WAS challenging!

BackTable of ContentsNext