How to Get the Last Item in a JavaScript Array [Quick Tip]

JavaScript - Get last item in array

This quick article will show you how to get the last item in an array in the JavaScript programming language.

Arrays and Array Indexes in JavaScript

Arrays are an ordered list of items. Each item in the array has a numerical index that defines its permission in the array.

The first index is index 0 (indexes start counting at 0, not 1!), so the last index is the array’s length; subtract 1.

Getting the Last Item in an Array

So, to get the last item in an array, we just have to find out the array’s length, subtract one, and get the item at that index.

This only works if the array is populated, of course.

Here it is in JavaScript Code:

# Define an array
var myArray = ['blue', 'green', 'pink'];

#Check that the array has items in it.  If the array length is 0 then the if statement will fail, if it is 1 or more it will succeed
if(array.length) {
    # Get the last item in the array
    var lastItem = myArray(myArray.length - 1)
}

And that’s all there is to it. The array.length property will return how many items are in the array, allowing you first to check that the array is populated before trying to access items in it, and secondly, use the length of the array to find the last index and access the value stored there.

Want to remove an element from an array? Here’s our article on how to do it.

SHARE:
nv-author-image

Brad Morton

I'm Brad, and I'm nearing 20 years of experience with Linux. I've worked in just about every IT role there is before taking the leap into software development. Currently, I'm building desktop and web-based solutions with NodeJS and PHP hosted on Linux infrastructure. Visit my blog or find me on Twitter to see what I'm up to.

Leave a Reply

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