JavaScript Array pop() Method

JavaScript array pop() function is “used to remove the last element from an array and returns that element”. It changes the original array.

Syntax

array.pop()

Parameters

None.

Return Value

It returns the removed element.

Example 1

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.

Javascript Array Pop Example | Array.prototype.pop() Tutorial

We can see that the item is removed, and the length of an array is modified.

Example 2

We can also perform the same operation with the integers of an array.

let numArr = [1, 3, 4, 5, 9];
let removedItem = numArr.pop();

console.log('The remaining items are: ', numArr);
console.log('The removed item is: ', removedItem);

Output

Array.prototype.pop() Tutorial

Example 3

let strArr = ['stan', 'bruce', 'warren', 'michael'];
let removedItem = strArr.pop();

console.log('The remaining items are: ', strArr);
console.log('The removed item is: ', removedItem);

Output

Javascript Array Pop() method tutorial

Example 4

If you call the pop() method on an empty array, it returns undefined. The length of the array becomes zero.

const numbers = [];
const last = numbers.pop();

console.log(last);
console.log(numbers.length);

Output

undefined
0

Example 5

The call() method is a predefined JavaScript method. With call(), an object can use a method belonging to another object. You can use the call() or apply() to call the pop() method on an array-like object.

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 }

That’s it.

1 thought on “JavaScript Array pop() Method”

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.