Array.pop()
The Array.pop()
method in JavaScript removes the last element from an array and returns that element. This method modifies the original array by reducing its length by one.
Syntax
array.pop()
Parameters
The pop()
method does not take any parameters.
Return Value
The pop()
method returns the last element of the array. If the array is empty, it returns undefined
.
Examples
1. Removing the Last Element
This example demonstrates how to remove the last element of an array using the pop()
method.
const fruits = ["apple", "banana", "cherry"];
const lastFruit = fruits.pop();
console.log(lastFruit); // Output: "cherry"
console.log(fruits); // Output: ["apple", "banana"]
Output
cherry
[ 'apple', 'banana' ]
The last element, "cherry"
, is removed from the array and returned by the pop()
method.
2. Using pop()
on an Empty Array
If the array is empty, the pop()
method returns undefined
.
const emptyArray = [];
const removedElement = emptyArray.pop();
console.log(removedElement); // Output: undefined
console.log(emptyArray); // Output: []
Output
undefined
[]
The array remains unchanged, and undefined
is returned.
3. Using pop()
in a Loop
You can use the pop()
method in a loop to empty an array.
const numbers = [1, 2, 3, 4, 5];
while (numbers.length > 0) {
console.log(numbers.pop());
}
console.log(numbers); // Output: []
Output
5
4
3
2
1
[]
Each call to pop()
removes and returns the last element of the array until it is empty.
4. Using pop()
in a Function
You can use the pop()
method to build utility functions, such as retrieving and removing the last element of an array.
function removeLastItem(array) {
return array.pop();
}
const colors = ["red", "green", "blue"];
const lastColor = removeLastItem(colors);
console.log(lastColor); // Output: "blue"
console.log(colors); // Output: ["red", "green"]
Output
blue
[ 'red', 'green' ]
The removeLastItem()
function uses pop()
to remove and return the last element of the array.