Do you want to know how to get the last item in an array in Node.js?

You need to get the index of the last value in the array. And you can get that index value 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 example.

Given this array of 5 different 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]

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.

Build A Hacker News Clone
Learn how to build and deploy a full-stack, production-ready application with React.js, Node.js, and MongoDB.
View Course

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!