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,
- Create an array
arr
with numeric values [1, 2, 3, 4, 5]. - Use
pop()
to remove the last element of the array. - Store the removed element in
removedElement
. - Log
removedElement
and the modified arrayarr
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,
- Create an empty array
arr
. - Use
pop()
to attempt to remove the last element of the array. - Store the result in
result
. - Log
result
and the modified arrayarr
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,
- Create an array
arr
with mixed values [1, 'apple', true, null]. - Use
pop()
to remove the last element of the array. - Store the removed element in
removedElement
. - Log
removedElement
and the modified arrayarr
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.