Free UI Resources - UI Dev Made Easy
Javascript

Javascript Array Methods – .pop()

.pop()

The .pop() method is a built-in function in JavaScript that allows you to remove the last element from an array. It’s a straightforward way to modify the array by removing an element from the end.

Here’s the basic syntax of the .pop() method:

const removedElement = array.pop();

The .pop() method removes the last element from the array and returns that element. After the removal, the length of the array decreases by one.

Here’s an example to illustrate how .pop() works:

const fruits = ['apple', 'banana', 'orange'];

const removedFruit = fruits.pop();

console.log(fruits);        // Output: ['apple', 'banana']
console.log(removedFruit);  // Output: 'orange'

In this example, the .pop() method removes the string 'orange' from the end of the fruits array and returns that string.

Keep in mind the following points when using .pop():

  1. Modifies Original Array: The .pop() method modifies the original array in-place by removing the last element.
  2. Return Value: The .pop() method returns the element that was removed from the end of the array.
  3. Empty Array: If the array is empty, calling .pop() will return undefined and have no effect on the array.
  4. Usage with Length: You can achieve similar results by using the .length property of the array. For example, array.length = array.length - 1 would remove the last element. However, using .pop() is more concise and expressive.
  5. Mutability: Since .pop() modifies the original array, make sure to use it when you intend to remove an element from the end.

In summary, the .pop() method is a simple and effective way to remove the last element from an array. It’s commonly used when you want to manipulate arrays by removing the last item, such as implementing stacks or maintaining dynamic lists of items.

back to top