JavaScript pop() method


The pop() method in JavaScript is used to remove the last element from an array. It modifies the original array by removing the element and returns the removed element. If the array is empty, it returns undefined.

Syntax:

array.pop()

Return Value:

  • The removed element from the array.
  • If the array is empty, pop() returns undefined.

Key Points:

  • Modifies the original array: The pop() method alters the array by removing the last element.
  • Returns the removed element: You can capture the value of the removed element.
  • If array is empty: Calling pop() on an empty array returns undefined.

Example 1: Removing the last element

let fruits = ['apple', 'banana', 'orange']; let removedFruit = fruits.pop(); console.log(fruits); // ['apple', 'banana'] console.log(removedFruit); // 'orange' (the removed element)

Example 2: Using pop() on an empty array

let emptyArray = []; let result = emptyArray.pop(); console.log(result); // undefined

Example 3: Using pop() in a loop

let numbers = [1, 2, 3, 4]; while (numbers.length > 0) { console.log(numbers.pop()); // prints 4, 3, 2, 1 (in this order) } console.log(numbers); // []

Performance Consideration:

  • Time complexity: The time complexity of pop() is O(1), which means it removes the element in constant time since it only needs to remove the last element.

Summary:

  • pop() is used to remove the last element from an array, modifying the original array. It returns the removed element, and if the array is empty, it returns undefined. It's a simple and efficient way to shrink an array by one element from the end.