w3docs logo
  1. Snippets
  2. JavaScript
  3. How to Get the Last Item in an Array

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:

w3docs logo Javascript getting the last item is the length property
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:

w3docs logo Javascript slice method return all items
let myArr = [1, 2, 3, 4, 5]; let arr = myArr.slice(-1)[0]; console.log(arr);

or

w3docs logo Javascript slice method return all items
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:

w3docs logo Javascript pop method return array last item
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?