Developed By
Gautam Kumar - Full stack developer
DEEP DIVE INTO
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.
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.
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.