menu

JavaScript/Typescript - 16 Topics

DEEP DIVE INTO

JavaScript/Typescript

Topic:pop() method

menu

In JavaScript, the pop() method removes the last element from an array and returns that element. This method modifies the original array by removing the last item, and if the array is empty, it will return undefined.

Here's the basic syntax of the pop() method:

javascriptconst removedElement = array.pop();
  • array: The array from which you want to remove the last element.

  • removedElement: The element that was removed from the array.

Here's an example of how pop() works:

javascriptconst fruits = ['apple', 'banana', 'cherry'];

const lastFruit = fruits.pop();

console.log(fruits);      // Outputs: ['apple', 'banana']
console.log(lastFruit);  // Outputs: 'cherry' (the removed element)

In this example, the pop() method removes the last element ('cherry') from the fruits array and assigns it to the lastFruit variable.

The pop() method is commonly used when you want to remove and retrieve elements from the end of an array, such as implementing a stack data structure.

Working Example

1280 x 720 px