There are different ways to get to an array’s last element in JavaScript. In this shot, we see two such ways.
length
propertyThe length
property of an array specifies the number of elements in the array. In JavaScript, an array index starts from 0, and the length
property starts the counting from 1. This results in one number greater than the total index values. Therefore, we must access the array index by subtracting 1 from its length to get the last index.
fruits
with three elements.length
property and subtract 1 from it. We save the result in the lastItem
variable.lastItem
on the console.at()
methodThe at
method works in the same way as a regular array index arr[n]
.
The only difference is that we can pass a negative integer, -1, to get the array’s last member.
We need to keep in mind that, unlike the
length
property, theat
method is a new ECMAScript feature released in 2022. Therefore, not all browsers support it.
fruits
with three elements.at()
method and pass -1
to it. We save the result in the lastItem
variable.lastItem
on the console.