JavaScript Array pop() method is used to remove the last element from an array and return that element. It changes the length of the array and modifies the original array.
Syntax
array.pop()
Parameters
None.
Return Value
It returns the removed element. If the array is empty, undefined is returned.
Visual RepresentationExample 1: How to Use Array pop() Method
let countries = ["UK", "US", "India","Israel", "Mexico"];
let removedItem = countries.pop();
console.log('The remaining items are: ', countries);
console.log('The removed item is: ', removedItem);
console.log('length of countries array: ',countries.length);
Output
The remaining items are: [ 'UK', 'US', 'India', 'Israel' ]
The removed item is: Mexico
Length of countries array: 4
Example 2: Using an empty array
let countries = [];
let removedItem = countries.pop();
console.log(removedItem);
console.log(countries.length);
Output
undefined
0
Example 3: Removing an element from an Array Of Objects
let apps = [
{ name: 'Amazon', value: 1 },
{ name: 'Amazon Prime', value: 21 },
{ name: 'Amazon Music', value: 10 },
{ name: 'Amazon Go', value: 100 },
{ name: 'Amazon Alexa', value: 13 }
];
removedItem = apps.pop();
console.log('The remaining items are: ', apps);
console.log('The removed item is: ', removedItem);
The last item of an array is removed, and we can get that element.
The remaining items are: [
{ name: 'Amazon', value: 1 },
{ name: 'Amazon Prime', value: 21 },
{ name: 'Amazon Music', value: 10 },
{ name: 'Amazon Go', value: 100 }
]
The removed item is: { name: 'Amazon Alexa', value: 13 }
Example 4: Using an array-like objects
let obj = {
0: "k",
1: "b",
2: "l",
length: 3
};
let last = Array.prototype.pop.call(obj);
console.log(last);
console.log(obj);
Output
l
{ '0': 'k', '1': 'b', length: 2 }
Browser compatibility
- Google Chrome 1 and above
- Edge 12 and above
- Firefox 1 and above
- Opera 4 and above
- Safari 1 and above