TypeScript Array pop()
Syntax & Examples

Array.pop() method

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


Syntax of Array.pop()

The syntax of Array.pop() method is:

pop(): T | undefined

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

Return Type

Array.pop() returns value of type T | undefined.



✐ Examples

1 Using pop() to remove the last element

The pop() method can be used to remove the last element from an array.

For example,

  1. Create an array arr with numeric values [1, 2, 3, 4, 5].
  2. Use pop() to remove the last element of the array.
  3. Store the removed element in removedElement.
  4. Log removedElement and the modified array arr to the console.

TypeScript Program

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

Output

5
[1, 2, 3, 4]

2 Using pop() on an empty array

The pop() method returns undefined when called on an empty array.

For example,

  1. Create an empty array arr.
  2. Use pop() to attempt to remove the last element of the array.
  3. Store the result in result.
  4. Log result and the modified array arr to the console.

TypeScript Program

const arr = [];
const result = arr.pop();
console.log(result); // undefined
console.log(arr); // []

Output

undefined
[]

3 Using pop() with mixed data types

The pop() method can be used on an array with mixed data types to remove the last element.

For example,

  1. Create an array arr with mixed values [1, 'apple', true, null].
  2. Use pop() to remove the last element of the array.
  3. Store the removed element in removedElement.
  4. Log removedElement and the modified array arr to the console.

TypeScript Program

const arr = [1, 'apple', true, null];
const removedElement = arr.pop();
console.log(removedElement); // null
console.log(arr); // [1, 'apple', true]

Output

null
[1, 'apple', true]

Summary

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