Accessing the Last Array Element in JavaScript

To access the last element of an array in JavaScript, you can use the length property or negative indexing techniques. Since JavaScript arrays are zero-indexed, the last element is always at the index equal to array.length - 1.

1. Using array.length - 1

This is the most straightforward way to access the last element.

let fruits = ['Apple', 'Banana', 'Orange'];
let lastFruit = fruits[fruits.length - 1];
console.log(lastFruit); // Output: 'Orange'
  • Explanation: The length property gives the number of elements in the array. Subtracting 1 gives you the index of the last element.

2. Using slice()

The slice() method can also be used to access the last element by slicing from the end.

let lastElement = fruits.slice(-1)[0];
console.log(lastElement); // Output: 'Orange'
  • Explanation: slice(-1) returns the last element as an array. [0] is used to access that element.

3. Using at() (ES2022)

The at() method, introduced in ES2022, allows for more intuitive access to elements using negative indices.

let lastFruit = fruits.at(-1);
console.log(lastFruit); // Output: 'Orange'
  • Explanation: at(-1) directly accesses the last element, making the code more readable.

Practical Tips

  • Index Boundaries: Remember that accessing array[array.length] will return undefined since arrays are zero-indexed.
  • Negative Indexing: The at() method provides a more elegant solution for negative indexing compared to older methods.