The pop() method in JavaScript is used to remove the last element from an array and returns that element. This method changes the length of the array.
Syntax
array.pop();
Return Value
Return Type | Description |
---|---|
Any | The removed element from the array. |
Example 1: Using pop() to Remove the Last Element
This code demonstrates how to use the pop() method to remove the last element from an array.
let Arr = [ 10, 20, 30, 40, 50 ]; let lastItem = Arr.pop(); console.log(Arr); console.log(lastItem);
Output:
[ 10, 20, 30, 40 ]
50
Example 2: Using pop() on an Empty Array
If the array is empty, pop()
returns undefined
.
let emptyArr = []; let result = emptyArr.pop(); console.log(result);
Output:
undefined
Example 3: Using pop() in a Loop
You can use pop()
in a loop to remove elements from an array one by one.
let Arr = [1, 2, 3, 4, 5]; while (Arr.length > 0) { console.log(Arr.pop()); }
Output:
5
4
3
2
1
Supported Browsers
Chrome | Edge | Firefox | Opera | Safari |
---|---|---|---|---|
1 | 12 | 1 | 4 | 1 |