Categories
JavaScript Answers

How to Get the Last Item in an Array?

Spread the love

Getting the last item in an array is something that we’ve to do sometimes in our JavaScript code.

In this article, we’ll look at how to get the last item in a JavaScript array.

Use the length Property

One way to get the last item of an array is to use the length property of an array.

For instance, we can write:

const arr = ['apple', 'orange', 'grape']
const last = arr[arr.length - 1]
console.log(last)

We use arr[arr.length — 1] to get the last item in the arr array.

Since JavaScript array index starts with 0, arr.length — 1 is the index of the last item of the array.

Therefore, the value of last is 'grape' .

The Array.prototype.slice Method

We can call an array’s slice method to get a part of the array.

Therefore, we can write:

const arr = ['apple', 'orange', 'grape']
const [last] = arr.slice(-1)
console.log(last)

We call arr.slice(-1) to return an array with the last item.

-1 is the index of the last item of the array.

Then we destructure the returned array and log the value with console.log .

The console log should be the same as the previous example.

Also, we can use slice with pop to return the last item of the array.

To do this, we write:

const arr = ['apple', 'orange', 'grape']
const last = arr.slice(-1).pop()
console.log(last)

pop remove an item from the end of the array and returns that item.

So we get the same results as the previous examples.

The Array.prototype.pop Method

We can just use the pop method without slice if we don’t care that the original array will have the last element removed.

For instance, we can write:

const arr = ['apple', 'orange', 'grape']
const last = arr.pop()
console.log(last, arr)

arr.pop removes the last item from arr and returns it.

And so last is 'grape' and arr is [“apple”, “orange”] .

Conclusion

We can use the length property of a JavaScript array, or its slice and pop methods to get the last item from an array.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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