How to Get the Last Item in an Array

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:

let myArr = [1, 2, 3, 4, 5];
let arr = myArr[myArr.length - 1];
console.log(arr);

Another succinct method is used. The slice() method returns a new array copying to it all the items from index start to the end:

let myArr = [1, 2, 3, 4, 5];
let arr = myArr.slice(-1)[0];
console.log(arr);

or

let myArr = [1, 2, 3, 4, 5];
let arr = myArr.slice(-1).pop();
console.log(arr);

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:

let myArr = [1, 2, 3, 4, 5];
let arr = myArr.pop();
console.log(arr);

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.

Do you find this helpful?

Related articles