Course contentsShow
← JavaScript
Lesson 1992 of 2,72341. Modern JavaScript Features (ES2020+)Free lesson

The at() Method: Negative Indexing

Learn how at() enables negative indexing to access array elements from the end, replacing awkward arr[arr.length - 1] patterns.

The at() Method: Negative Indexing

You'll learn how to access array elements from the end using at() with negative indices, making your code cleaner and more readable.

The Old Way Was Awkward

For years, JavaScript developers had to write clunky expressions like arr[arr.length - 1] to get the last element of an array, or arr[arr.length - 2] for the second-to-last. It works, but it's verbose and breaks the flow of reading code.

Negative Indexing with at()

The at() method, introduced in ES2022, accepts negative integers to count backwards from the end of an array. Think of it like a circular tape measure that can go in reverse.

const fruits = ['apple', 'banana', 'cherry', 'date'];

// Old way
const last = fruits[fruits.length - 1];        // 'date'
const secondLast = fruits[fruits.length - 2];  // 'cherry'

// New way with at()
const last = fruits.at(-1);        // 'date'
const secondLast = fruits.at(-2);  // 'cherry'

How It Works

Positive indices work exactly as before: at(0) gets the first element, at(1) the second. But negative indices count backward: at(-1) is the last element, at(-2) is second-to-last, and so on.

const nums = [10, 20, 30, 40, 50];

console.log(nums.at(0));   // 10 (first)
console.log(nums.at(-1));  // 50 (last)
console.log(nums.at(-3));  // 30 (third from end)

If the index is out of bounds (positive or negative), at() returns undefined, just like regular bracket notation.

Key Takeaway: Use at() with negative indices to access array elements from the end cleanly—arr.at(-1) is far more readable than arr[arr.length - 1].