javascript
  1. javascript-pop

JavaScript pop()

The pop() method is a built-in function in JavaScript which removes the last element from an array and returns that element. It modifies the original array by removing the last element and updating the length of the array. This method can be used to implement a Last-In-First-Out (LIFO) data structure where elements are popped off the stack in reverse order that they were pushed.

Syntax

The syntax for using pop() method is:

arr.pop()

Here, arr is an array object and pop() is the method name.

Example

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Array Pop Example</title>
</head>
<body>

<!-- Placeholder for displaying the output -->
<p id="output"></p>

<script>
    // Array
    let fruits = ['apple', 'banana', 'orange'];

    // Remove the last element and store it in a variable
    let lastFruit = fruits.pop();

    // Display the removed element
    document.getElementById("output").innerHTML += "Removed Fruit: " + lastFruit + "<br>";

    // Display the modified array
    document.getElementById("output").innerHTML += "Remaining Fruits: " + fruits.join(', ');
</script>

</body>
</html>
Try Playground

In this example, the pop() method is used to remove the last element 'orange' from the fruits array and store it in a variable lastFruit. The output of lastFruit is 'orange' and the updated fruits array contains only ['apple', 'banana'].

Output

The output of pop() method is the last element of the array that is removed. Also, the pop() method modifies the original array by removing the last element and updating the length of the array.

Explanation

The pop() method works by modifying the original array. It removes the last item from the array and returns it. If the array is empty, the pop() method returns undefined.

Use

The pop() method is useful when we need to remove the last element of an array. It is often used to implement a stack data structure where elements are added and removed in a Last-In-First-Out (LIFO) order.

Important Points

  • The pop() method modifies the original array by removing the last element and updating the length of the array.
  • If the array is empty, the pop() method returns undefined.
  • The pop() method can be used to implement a stack data structure where elements are added and removed in a Last-In-First-Out (LIFO) order.

Summary

The pop() method is a useful method in JavaScript that is used to remove the last element of an array and return that element. It modifies the original array by removing the last element and updating the length of the array. The pop() method is often used to implement a stack data structure where elements are added and removed in a Last-In-First-Out (LIFO) order.

Published on: