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

작성자

카테고리:

← 피드로
DEV Community · Akash Singh · 2026-07-27 개발(SW)
Cover image for A Cleaner Way to Access the Last Element of an Array in JavaScript

Akash Singh

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!

원문에서 계속 ↗

코멘트

답글 남기기

이메일 주소는 공개되지 않습니다. 필수 필드는 *로 표시됩니다