How to Get the Last Item in an Array
Read the tutorial and learn the methods of getting the last item in the array. Get to know the methods and their peculiarities to find the best solution.
In this tutorial, we will suggest three methods of getting the last item in a JavaScript Array.
The first method for getting the last item is the length property. You can pick the last item by doing the following:
Javascript getting the last item is the length property
Another succinct method is used. The slice() method returns a new array copying to it all the items from index start to the end:
Javascript slice method return all items
or
Javascript slice method return all items
Both of them will return undefined if the array is empty.
The pop() method is also used; however, keep in mind that it removes the last element of the array and returns that element:
Javascript pop method return array last item
Arrays
Javascript array is a variable holding multiple values simultaneously. JavaScript arrays are zero-indexed, where the first element is at index 0, and the last element is at the index equivalent to the value of the length property minus 1. An invalid index number returns undefined.