When working with JavaScript arrays, it is common to come across the need to remove the last item from an array. Whether you want to remove the last element permanently or just temporarily, there are a few different approaches you can take.
Method 1: Using the pop() method
The simplest way to remove the last item from an array is by using the pop()
method. This method removes the last element from an array and returns that element.
// Example array
var fruits = ['apple', 'banana', 'orange'];
// Removing the last item using pop()
var lastItem = fruits.pop();
console.log(fruits); // Output: ['apple', 'banana']
console.log(lastItem); // Output: 'orange'
Method 2: Using the splice() method
Another way to remove the last item from an array is by using the splice()
method. This method allows you to remove elements from an array by specifying the starting index and the number of elements to remove.
// Example array
var fruits = ['apple', 'banana', 'orange'];
// Removing the last item using splice()
fruits.splice(-1, 1);
console.log(fruits); // Output: ['apple', 'banana']
Method 3: Using the slice() method
If you want to remove the last item from an array without modifying the original array, you can use the slice()
method. This method returns a new array containing the selected elements.
// Example array
var fruits = ['apple', 'banana', 'orange'];
// Removing the last item using slice()
var newArray = fruits.slice(0, -1);
console.log(newArray); // Output: ['apple', 'banana']
console.log(fruits); // Output: ['apple', 'banana', 'orange']
Now that you have learned three different methods to remove the last item from an array, you can choose the one that best suits your needs. Whether you want to permanently remove the last element, modify the original array, or create a new array without the last item, these methods will help you achieve your desired outcome.
Leave a Reply