JavaScript pop(): Remove the Last Element from an Array

The JavaScript pop() method is used when we need to remove the last element from an array. For example:

HTML with JavaScript Code
<!DOCTYPE html>
<html>
<body>

   <p>Array before pop():-<br><span id="xyz"></span></p>
   <hr>
   <p>Array after pop():-<br><span id="abc"></span></p>

   <script>
      const cities = ["Tokyo", "Bangkok", "Dubai", "Berlin", "Frankfurt"];

      document.getElementById("xyz").innerHTML = cities;
      cities.pop();
      document.getElementById("abc").innerHTML = cities;
   </script>
   
</body>
</html>
Output

Array before pop():-


Array after pop():-

The pop() method is used to remove and return the last element of an array. An array cities with five elements is declared in this code.

The innerHTML property is used to display the cities array before applying the pop() method, and it is used again to display the array after the pop() method has been applied.

cities.pop() is used in the script to remove the last element ("Frankfurt") from the cities array, and the updated array is displayed using

document.getElementById("abc").innerHTML

JavaScript pop() syntax

The syntax of the pop() method in JavaScript is:

array.pop()

The pop() method returns the removed element from the array. For example:

HTML with JavaScript Code
<!DOCTYPE html>
<html>
<body>

   <p id="res"></p>

   <script>
      const x = ["Tokyo", "Bangkok", "Dubai", "Berlin", "Frankfurt"];
      document.getElementById("res").innerHTML = x.pop();
   </script>
   
</body>
</html>
Output

This code defines an array x with five elements. The pop() method is then called on the array, which removes the last element from the array and returns it. The returned element (in this case, "Frankfurt") is then displayed in the paragraph element with the id "res".

JavaScript Online Test


« Previous Tutorial Next Tutorial »


Liked this post? Share it!