The Array.pop()
method is a built-in JavaScript function that removes the last element from an array and returns that element. It modifies the original array and reduces its length by one.
Syntax
arr.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 not empty and undefined
if the array is empty.
Example 1: The pop() method removes the last element and returns it. The original array is updated.
let arr = [10, 20, 30, 40, 50]; let lastItem = arr.pop(); console.log(lastItem); // Output: 50 console.log(arr); // Output: [10, 20, 30, 40]
Example 2: Using pop()
on an Empty Array. When the array is empty, pop() returns undefined without causing an error.
let arr = []; let poppedItem = arr.pop(); console.log(poppedItem); // Output: undefined console.log(arr); // Output: []
Example 3: The pop() method is used in a loop to process and remove tasks from the end of the array.
let arr = [10, 20, 30, 40, 50]; while (arr.length > 0) { let lastItem = arr.pop(); console.log(lastItem); } /* Output: 50 40 30 20 10 */
Example 5: Using pop()
method on a Sparse Array
let arr = [1, , 3, , 5]; let lastItem = arr.pop(); console.log(lastItem); // Output: 5 console.log(arr); // Output: [1, , 3, ]
Supported Browsers
Browser | Support |
---|---|
Chrome | 1+ |
Firefox | 1+ |
Safari | 1+ |
Edge | 12+ |
Opera | 4+ |
Internet Explorer | 5.5+ |