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

Console
Get last element using length property

Explanation

  • Line 1: We create an array fruits with three elements.
  • Line 3: We get the array’s length using the length property and subtract 1 from it. We save the result in the lastItem variable.
  • Line 5: We print the value of lastItem on 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 length property, the at method is a new ECMAScript feature released in 2022. Therefore, not all browsers support it.

Example

Console
Get array's last element using at() method

Explanation

  • Line 1: We create an array fruits with three elements.
  • Line 3: We use the at() method and pass -1 to it. We save the result in the lastItem variable.
  • Line 5: We print the value of lastItem on the console.

Free Resources