How do you get the last item in an array using JavaScript?

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 1.

Let's go over a quick code example.

Given this array of five string items named myArray:

      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"

The 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!