JavaScript Arrays pop


Remove Array Elements

You can use the pop method of arrays to remove the last element of an array. When looking at JavaScript code the last element is the one on the right and when you think of a stack of dishes the last element is the one on top. You can add elements to an array with the push method. The following modified code based on code from w3schools.com.

<!DOCTYPE html>
<html>
<body>
<p>The pop method removes the last element from an array.</p>
<button onclick="myFunction()">Pop a fruit</button>
<p id="demo"></p>
<script>
var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits;

function myFunction() {
    fruits.pop();
    document.getElementById("demo").innerHTML = fruits;
}
</script>
</body>
</html>

Here is another example.

<!DOCTYPE html>
<html>
<body>
<h3>JavaScript Arrays</h3>
<p>Removing and Displaying objects.</p>
<button onclick="fruits.forEach(myFunction)">Display Fruits</button>
<button onclick="myPopFunction()">Pop One Fruit</button>
<p>Name => Value</p>
<p id="demo"></p>
<script>
// display the objects when user clicks button
var demoP = document.getElementById("demo");
var fruits = [ { name:"Banana", value:3 },
               { name:"Orange", value:2 },
               { name:"Apple", value:7 }, 
	       { name:"Mango", value:4 } 
             ];
function myFunction(item) {
    console.log(item.name + " => " + item.value);  // F12 in Chrome displays console
    demoP.innerHTML = demoP.innerHTML + item.name + " => " + item.value + "<br />";
}
function myPopFunction() {
    fruits.pop();
}
</script>
</body>
</html>

Leave a comment

Your email address will not be published. Required fields are marked *