Press ESC to close

JavaScript pop

0 1338

In this lesson we will cover the pop method in JavaScript, which is useful for deleting elements in an array.

In the previous lesson we have dealt with the push method and we have seen how to add elements to our queued array, now we will see how to delete them.

So to remove or add elements to the end of an array in JavaScript you can use the pop () and push () methods.

The syntax of the pop method is as follows:


JavaScript pop – example 1

Create an array that contains elements and delete the last element.

In this first example on the use of the pop () method, I first create an array that contains, for example, school objects, as in the previous example of the push.

Then with the pop method I delete the last element.

So here’s the simple example code:

var objectsSchools = ['eraser', 'notebook', 'pencil'];


console.log (school objects);

JavaScript pop – example 2

Let’s take a demonstrative example of the pop () method.

For example, suppose you have the days of the week from Monday to Sunday stored in an array. Every time I click on a button inserted in the html page, I remove one day, the last.

Do the test by clicking on the button below several times, you will notice that each time the last day will be removed:

To make the script I create an array that contains the days of the week, for example

days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"].

After, I define a function called remove and insert the instructions to call the pop () method which deletes the days from the array and warns the user with an alert that the operation was successful. So with a for loop I display all the days left.

Here is the sample JavaScript code that uses the pop method of JavaScript:

var days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"];
function removeElement() {
    alert ("I remove a day");
    for (var i = 0; i < days.length; i++) {

To invoke this function, I insert the action when clicking on the remove day button.

So in the html page I use the following code:

<input type="submit" value="Remove a day" onclick="removeElement()">


In this lesson we have covered some simple examples that use the JavaScript pop method.

Some useful links

JavaScript tutorial

JavaScript Calculator

Object in JavaScript

For in loop

Caesar cipher decoder

Slot Machine in JavaScript

Other stories

JavaScript shift and unshift

Next Story

JavaScript array push

Previous Story