The first thing you need to get is the index value of the last item in the array. That value can be obtained dynamically with this method:
array[array.length - 1].
By using that method, you can get the index of the last value of an array even if you don't know the
length beforehand. The index of the last item is simply the length of the array subtracted by
Let's go over a quick code example.
Given this array of five string items named
const myArray = ["Arbys", "McDonalds", "Wendys", "Taco Bell", "Chick-fil-A"]
You can get the last value of this array of delicious food establishments with this method:
const lastItem = myArray[myArray.length - 1] // returned value = "Chick-fil-A"
myArray.length - 1 method comes out to
4 in this case, which is the index of the last value. If you
console.log() the lastItem variable, the
"Chick-fil-A" string value will be logged.
Try this out with arrays that have varying lengths and see that the solution works in all cases.
Hopefully, this was helpful in your coding endeavors.
Thanks for reading and happy coding!