The pop() method removes the last element from an array and returns that element. This method changes the length of the array.
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.
Array.pop() returns value of type T | undefined
.
The pop() method can be used to remove the last element from an array.
For example,
arr
with numeric values [1, 2, 3, 4, 5].pop()
to remove the last element of the array.removedElement
.removedElement
and the modified array arr
to the console.const arr = [1, 2, 3, 4, 5];
const removedElement = arr.pop();
console.log(removedElement); // 5
console.log(arr); // [1, 2, 3, 4]
5 [1, 2, 3, 4]
The pop() method returns undefined when called on an empty array.
For example,
arr
.pop()
to attempt to remove the last element of the array.result
.result
and the modified array arr
to the console.const arr = [];
const result = arr.pop();
console.log(result); // undefined
console.log(arr); // []
undefined []
The pop() method can be used on an array with mixed data types to remove the last element.
For example,
arr
with mixed values [1, 'apple', true, null].pop()
to remove the last element of the array.removedElement
.removedElement
and the modified array arr
to the console.const arr = [1, 'apple', true, null];
const removedElement = arr.pop();
console.log(removedElement); // null
console.log(arr); // [1, 'apple', true]
null [1, 'apple', true]
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.