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:

Download  Run Code

 
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.

Download  Run Code

 
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).

Download  Run Code

 
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.