How to access the last element in an array in JavaScript
There are different ways to get to an array’s last element in JavaScript. In this shot, we see two such ways.
1. Using the length property
The 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.
Example
Explanation
- Line 1: We create an array
fruitswith three elements. - Line 3: We get the array’s length using the
lengthproperty and subtract 1 from it. We save the result in thelastItemvariable. - Line 5: We print the value of
lastItemon the console.
2. Using the at() method
The 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
lengthproperty, theatmethod is a new ECMAScript feature released in 2022. Therefore, not all browsers support it.
Example
Explanation
- Line 1: We create an array
fruitswith three elements. - Line 3: We use the
at()method and pass-1to it. We save the result in thelastItemvariable. - Line 5: We print the value of
lastItemon the console.