Remove Last Element form Array using pop() Method
This method is used to remove the last element of the array and returns the removed element. This function decreases the length of the array by 1 every time the element is removed.
Example 1: The below code is the basic implementation of the pop() method to remove elements from an array.
// JavaScript code to illustrate pop() function
// to remove array elements
let arr = ["shift", "splice", "filter", "pop"];
// Popping the last element from the array
let popped = arr.pop();
console.log("Removed element: " + popped);
console.log("Remaining elements: " + arr);
console.log("Array length: " + arr.length);
Output
Removed element: pop Remaining elements: shift,splice,filter Array length: 3
Example 2: The below code removes the elements from array using pop() method until the length of the array turns to 0.
// Declare and initialize an array
let array = ["pop", "splice", "filter", "shift"]
console.log("Original array: " + array)
// Loop run while array length not zero
while (array.length) {
// Remove elements from array
array.pop();
}
console.log("Array Length: " + array.length)
Output
Original array: pop,splice,filter,shift Array Length: 0
Remove elements from a JavaScript Array
Removing elements from a JavaScript array means taking out certain items from the array. This is a basic and important task in programming because it helps keep the array accurate and makes data handling easier. In this article, we will discuss few methods to remove elements from a JavaScript Array.