Method 1: Use index positioning
Use index positioning if you know the length of the array.
Let’s create an array:
const animals = [‘cat’, ‘dog’, ‘horse’]
Here we can see that the last item in this array is
To get the last item, we can access the last item based on its index:
const finalElement = animals;
JavaScrip arrays are zero-indexed. This is why we can access the
horse element with
animals. If you aren’t sure on what zero-indexed means, we’ll go over it later on in this tutorial.
This method of getting the final item in the array works if you know the length of the array.
But what if you don’t know the length of the array? This array,
animals, is very small. But you could have another array that has dozens of items in it, and you might not know its length.
Method 2: When you don’t know the array length
To get the last item in an array when you don’t know the length of that array:
const lastItem = animals[animals.length - 1];
lastItem variable now holds the value of
Let’s break down what’s happening in the above line. First of all, let’s just console log
If you aren’t familiar with the
length property, it returns the length of this array. This prints out
3, because there are
3 items in the array.
cat is at index
dog is at index
horse is at index
You might still be confused. We just learned that
animals[animals.length - 1]?
Let’s imagine for a moment that JS arrays were not zero-indexed, and we started counting from 1, which is the way we normally count things in the real world.
animals array, we could quickly start counting and say that
cat, the first item, has an index of 1,
dog has an index of
horse has an index of
3. The key insight here is that, in one-based indexing, the index of the last item is the length of the array. If the array has a length of 3, you know that the last element in the array has an index of
animals would evaluate to
animals[animals.length - 1];
Inside of the brackets,
animals.length - 1 evaluates to
2. We now have the last item in the array.
Thank you for reading!
If you enjoyed this post, join my coding club, where we tackle coding challenges together every Sunday and support each other as we learn new technologies.
If you have feedback or questions on this post, or find me on Twitter @madisonkanna.