The JavaScript Array pop() method removes the last element from an array and returns that element. This method changes the length of the array and is commonly used to remove elements from the end of an array.
For example, array.pop() is useful when you need to remove the last element of an array and also retrieve the removed element.
Syntax
The syntax for the Array.pop() method is:
array.pop()
Parameters
The Array.pop() method does not accept any parameters.
Return Value
The last element of the array, after removing it. If the array is empty, it returns undefined.
Examples of JavaScript Array.pop() Method
Example 1: Removing the Last Element of an Array
The pop() method removes and returns the last element from the array.
const fruits = ['apple', 'banana', 'mango'];
const lastFruit = fruits.pop();
console.log(lastFruit); // Output: "mango"
console.log(fruits); // Output: ['apple', 'banana']
Explanation: The pop() method removes 'mango', which is the last element of the fruits array, and returns it. The remaining elements in the array are 'apple' and 'banana'.
Example 2: Using pop() on an Empty Array
If pop() is used on an empty array, it returns undefined.
const emptyArray = [];
const result = emptyArray.pop();
console.log(result); // Output: undefined
console.log(emptyArray); // Output: []
Explanation: Since the array is empty, calling pop() returns undefined and does not modify the array.
Example 3: Modifying the Length of an Array with pop()
The pop() method alters the length of the array by removing the last element.
const numbers = [1, 2, 3, 4, 5];
numbers.pop();
console.log(numbers.length); // Output: 4
Explanation: After removing the last element (5), the array’s length is reduced from 5 to 4.
Example 4: Chaining pop() with Other Methods
The pop() method can be used alongside other array methods for more complex operations.
const stack = [10, 20, 30];
const poppedValue = stack.pop().toString();
console.log(poppedValue); // Output: "30"
console.log(stack); // Output: [10, 20]
Explanation: The pop() method removes the last element (30), converts it to a string, and returns "30", while the stack array is left with [10, 20].
Example 5: Using pop() with Nested Arrays
The pop() method can be used on nested arrays, allowing you to manipulate array elements inside arrays.
const nestedArray = [[1, 2], [3, 4], [5, 6]];
const lastArray = nestedArray.pop();
console.log(lastArray); // Output: [5, 6]
console.log(nestedArray); // Output: [[1, 2], [3, 4]]
Explanation: The pop() method removes and returns the last sub-array ([5, 6]), leaving the nestedArray with [[1, 2], [3, 4]].