Skip to content

How to get last element of an array in JavaScript?

New Course Coming Soon:

Get Really Good at Git

How do you get the last element of an array in JavaScript? Let's find out.

Are you wondering how to get last element of an array in JavaScript?

Suppose you have an array, like this:

const colors = ['red', 'yellow', 'green', 'blue']

In this case the array has 4 items.

You know you can get the first item using colors[0], the second using colors[1] and so on.

To get the last item without knowing beforehand how many items it contains, you can use the length property to determine it, and since the array count starts at 0, you can pick the last item by referencing the <array>.length - 1 item.

Here’s a simple example:

const lastItem = colors[colors.length - 1]

That was a simple explanation of how to get the last item of an array in JavaScript!

Are you intimidated by Git? Can’t figure out merge vs rebase? Are you afraid of screwing up something any time you have to do something in Git? Do you rely on ChatGPT or random people’s answer on StackOverflow to fix your problems? Your coworkers are tired of explaining Git to you all the time? Git is something we all need to use, but few of us really master it. I created this course to improve your Git (and GitHub) knowledge at a radical level. A course that helps you feel less frustrated with Git. Launching Summer 2024. Join the waiting list!
→ Get my JavaScript Beginner's Handbook
→ Read my JavaScript Tutorials on The Valley of Code
→ Read my TypeScript Tutorial on The Valley of Code

Here is how can I help you: