• JavaScript Video Tutorials

JavaScript - Array pop() Method



In JavaScript, the Array.pop() method is used to remove the last element from an array and returns that element. It modifies the original array by decreasing its length by one. This method can only remove one element in a single attempt.

By using this method, we can remove the element from the "end of an array". If the array is empty, it returns "undefined" as the result.

If we want to remove the first element of an array, use the JavaScript Array.shift() method.

Syntax

Following is the syntax of JavaScript Array pop() Method −

array.pop();

Parameters

This method does not accept any parameters.

Return value

This method returns the removed element, which is the last element of the array. If the array is empty, pop() returns undefined.

Examples

Example 1

In the following example, we are using the JavaScript Array pop() method to remove the last element from the array.

<html>
<body>
   <p id="demo"></p>
   <script>
      const animals = ["Lion", "Cheetah", "Tiger", "Elephant"];
      animals.pop();
      document.getElementById("demo").innerHTML = animals;
   </script>
</body>
</html>

Output

Lion,Cheetah,Tiger

Example 2

Here, we are removing the last element of the array and fetching the element that has been removed −

<html>
<body>
   <p id="demo"></p>
   <script>
      const animals = ["Lion", "Cheetah", "Tiger", "Elephant"];
      animals.pop();
      document.getElementById("demo").innerHTML = animals;
   </script>
</body>
</html>

Output

Lion,Cheetah,Tiger

Example 3

If the array is empty and we try to use the pop() method on it, this method will return undefined as a result.

<html>
<body>
   <p id="demo"></p>
   <script>
      const animals = [];
      let removed_element = animals.pop();
      document.getElementById("demo").innerHTML = removed_element;
   </script>
</body>
</html>

Output

undefined
Advertisements