A Cleaner Way to Access the Last Element of an Array in JavaScript

Most JavaScript developers access the last element of an array like this: const arr = [10, 20, 30, 40]; console.log(arr[arr.length - 1]); // 40 It works perfectly and is still a common approach. However, modern JavaScript provides a cleaner alternative: const arr = [10, 20, 30, 40]; console.log(arr.at(-1)); // 40 .at()? ✅ Cleaner and easier to read. ✅ Supports negative indexing. ✅ No need to calculate length - 1. ✅ Great for accessing elements from the end of an array. const arr = [10, 20, 30, 4
Most JavaScript developers access the last element of an array like this:
const arr = [10, 20, 30, 40];
console.log(arr[arr.length - 1]); // 40
Enter fullscreen mode Exit fullscreen mode
It works perfectly and is still a common approach.
However, modern JavaScript provides a cleaner alternative:
const arr = [10, 20, 30, 40];
console.log(arr.at(-1)); // 40
Enter fullscreen mode Exit fullscreen mode
Why use .at()?
- ✅ Cleaner and easier to read.
- ✅ Supports negative indexing.
- ✅ No need to calculate
length - 1. - ✅ Great for accessing elements from the end of an array.
More examples
const arr = [10, 20, 30, 40];
console.log(arr.at(-1)); // 40
console.log(arr.at(-2)); // 30
console.log(arr.at(-3)); // 20
Enter fullscreen mode Exit fullscreen mode
Instead of calculating indexes manually, you can directly access elements from the end of an array.
Final Thoughts
Both approaches are correct.
-
arr[arr.length - 1]is the classic and widely used approach. -
arr.at(-1)is a modern, more expressive alternative that improves readability.
Small JavaScript features like this can make your code cleaner over time.
💬 **Do you use .at() in your projects, or do you still prefer arr[arr.length - 1]? Let me know in the comments!
