JavaScript Tutorials

JavaScript Array pop()
Syntax & Examples

Array.pop() method

The pop() method of the Array class in JavaScript removes the last element from an array and returns that element.


Syntax of Array.pop()

The syntax of Array.pop() method is:

pop()

This pop() method of Array removes the last element from an array and returns that element.

Return Type

Array.pop() returns value of type Any.



✐ Examples

1 Using pop() method to remove and return the last element

In JavaScript, we can use the pop() method to remove and return the last element from an array.

For example,

  1. We define an array variable arr with elements [1, 2, 3, 4, 5].
  2. We use the pop() method on arr to remove and return the last element.
  3. The last element, which is 5, is removed from arr and stored in the variable removedElement.
  4. We log removedElement to the console using console.log() method.

JavaScript Program

const arr = [1, 2, 3, 4, 5];
const removedElement = arr.pop();
console.log(removedElement);

Output

5

2 Using pop() method on an empty array

If the array is empty, pop() method returns undefined.

For example,

  1. We define an empty array variable emptyArr.
  2. We use the pop() method on emptyArr.
  3. The pop() method returns undefined as the array is empty.
  4. We log the return value to the console using console.log() method.

JavaScript Program

const emptyArr = [];
const result = emptyArr.pop();
console.log(result);

Output

undefined

Summary

In this JavaScript tutorial, we learned about pop() method of Array: the syntax and few working examples with output and detailed explanation for each example.