If you’re wondering how to get the last element of an array in JavaScript, let’s find out.
Let’s say you have an array of colors like this:
const colors = ['red', 'yellow', 'green', 'blue'];
In this case, the array has 4 items.
You already know that you can get the first item using colors[0]
, the second item using colors[1]
, and so on. But how do you get the last item without knowing the number of items in the array?
You can use the length
property of the array to determine the number of items it contains. Since the array count starts at 0, you can get the last item by referencing the index array.length - 1
.
Here’s a simple code example:
const lastItem = colors[colors.length - 1];
That’s it! You now know how to get the last item of an array in JavaScript.