How to remove last item from array in JavaScript?

How to remove last item from array in JavaScript?

Hello Coders.

In this article, I will show a quick example of how to remove the last item from an array in JavaScript. We will learn about removing the last elements from array in JavaScript. 

There are two methods to remove the last array item. 

Using pop() Method

It is a simplest and easy to use method to remove the last element from array. This method returns the removed item from the original array. 

const arr = ['a,'b','c','d'];
const lastItem = arr.pop();
console.log(lastItem); // It will return d
console.log(arr); // original array ['a,'b','c']

As we can see, the pop() method returns the last item from the array but changes the original array also. If we use this method on an empty array, it will return undefined instead of making an error. Changing the original array can be difficult to use, especially if we have to use the same array multiple times. Alternatively, we can use the splice() method to do the same process but without changing the original array. the original

Using splice() Method

We also use this method to remove the last element from the array. This method will return a copy of the original array excluding the last item, without changing the original array. 

const arr = ['a','b','c','d'];
const withoutLastItem = arr.slice(0, -1); 
console.log(withoutLastItem); // ['a','b','c'];
console.log(arr); // original arr ['a','b','c','d']

The splice() method takes two parameters

  1. The first parameter means the index of the first item should be included in the new array.
  2. The second parameter means go up to the last item of the array but should not be included in the new array. 

 

Conclusion

In this short article, we have checked two methods to get the last item from the array. If you want to simply get the last item from an array, then you should use the pop() method because it returns only the removed item. But if you want a complete array excluding the last item of an array, then you should use the splice() method because it returns an array excluding the last element without changing the original array. 

Leave a Comment

Your email address will not be published. Required fields are marked *

Go To Top
×