In this example, the pop()
method is used to remove the last element 'orange' from the fruits
array and store it in a variable lastFruit
. The output of lastFruit
is 'orange' and the updated fruits
array contains only ['apple', 'banana'].
Output
The output of pop()
method is the last element of the array that is removed. Also, the pop()
method modifies the original array by removing the last element and updating the length of the array.
Explanation
The pop()
method works by modifying the original array. It removes the last item from the array and returns it. If the array is empty, the pop()
method returns undefined
.
Use
The pop()
method is useful when we need to remove the last element of an array. It is often used to implement a stack data structure where elements are added and removed in a Last-In-First-Out (LIFO) order.
Important Points
- The
pop()
method modifies the original array by removing the last element and updating the length of the array.
- If the array is empty, the
pop()
method returns undefined
.
- The
pop()
method can be used to implement a stack data structure where elements are added and removed in a Last-In-First-Out (LIFO) order.
Summary
The pop()
method is a useful method in JavaScript that is used to remove the last element of an array and return that element. It modifies the original array by removing the last element and updating the length of the array. The pop()
method is often used to implement a stack data structure where elements are added and removed in a Last-In-First-Out (LIFO) order.