Delete last element from an array in JavaScript
This post will discuss how to delete the last element from an array in JavaScript.
There are several ways to delete the last element from an array in JavaScript. Here are some examples:
1. Using pop() function
The pop() function deletes the last element of an array and returns the element. It modifies the original array and reduces its length by one. For example, if we have an array [1, 2, 3, 4, 5] and we want to delete the last element 5, we can do like:
|
1 2 3 4 5 6 7 |
var arr = [1, 2, 3, 4, 5]; // remove and return the last element var last = arr.pop(); console.log(arr); // [1, 2, 3, 4] console.log(last); // 5 |
This function is a simple and efficient way to delete the last element from an array, but it does not allow us to specify which element to remove or how many elements to remove.
2. Using splice() function
The splice() function adds or removes elements from an array and returns an array of the deleted elements. It modifies the original array and changes its length accordingly. To delete the last element of an array, we can use the syntax array.splice(-1, 1), where -1 is the index of the last element and 1 is the number of elements to remove.
|
1 2 3 4 5 6 7 |
var arr = [1, 2, 3, 4, 5]; // remove one element from the end var removed = arr.splice(-1, 1); console.log(arr); // [1, 2, 3, 4] console.log(removed); // [5] |
This function is more flexible than the pop() function, as it allows us to specify the index and the count of the elements to remove. However, it may not be as efficient as the pop() function, as it involves creating and returning a new array of the deleted elements.
3. Using slice() function
The slice() function returns a new array containing a portion of the original array. It does not modify the original array, but rather creates a shallow copy of it. To delete the last element of an array and return a new array without it, we can use the syntax array.slice(0, -1), where 0 is the start index and -1 is the end index (excluding).
|
1 2 3 4 5 6 7 |
var arr = [1, 2, 3, 4, 5]; // create a new array without the last element var newArr = arr.slice(0, -1); console.log(arr); // [1, 2, 3, 4, 5] console.log(newArr); // [1, 2, 3, 4] |
This function is useful if we want to keep the original array intact and create a new array without the last element. However, it may not be very efficient as it involves creating and copying a new array.
That’s all about deleting the last element from an array in JavaScript.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)