Array is a variable that holds different types of information in JavaScript. If, you want to remove some elements from the ending or last of the array. In this guide, we will show you how to remove the last element from an array in javascript.
How to Remove the Last Element From an Array in JavaScript
There are a few approaches to remove the last element from an array in javascript:
- Approach 1: Using the pop() method
- Approach 2: Using the
splice()
method - Approach 3: Using the slice() method
Approach 1: Using the pop() method
The pop()
method helps us to remove or delete the last element from the array and return it. It removes the last element and changes the original array.
Here is an example function of removing the last element from the array javascript using pop:
const lang = ["python", "php", "node"];
lang.pop();
console.log(lang); // ["python", "php"]
Approach 2: Using the splice()
method
The splice()
method can be used to remove elements from an array by specifying the start index and the number of elements to be removed. To remove the last element, you can use the array’s length as the start index and remove one element.
Here is an example function of removing last element from the array javascript using Splice:
// Example array
let myArray = [1, 2, 3, 4, 5];
// Remove the last element
myArray.splice(myArray.length - 1, 1);
// Display the modified array
console.log("Modified Array:", myArray);
Approach 3: Using the slice() method
The slice()
method returns a new array containing the selected elements from an existing array. To remove the last element, you can create a new array by specifying the start index as 0 and the end index as the length of the array minus 1.
Here is an example function of removing last element from the array javascript using slice():
// Sample array
let myArray = [1, 2, 3, 4, 5];
// Creating a new array without the last element using slice()
let newArray = myArray.slice(0, myArray.length - 1);
console.log("New array:", newArray);
console.log("Original array remains unchanged:", myArray);
Conclusion
That’s it; you have learned how to remove the last element from an array in javascript using the pop, splice, and slice method.