at() vs Bracket Notation
You'll learn when to choose at() over traditional bracket notation and why it shines with dynamic indices.
Both at() and bracket notation let you access elements in arrays (and strings), but they handle indices differently—especially negative ones.
How They Differ
With bracket notation, you write array[index]. It's familiar and fast, but it only accepts positive indices. If you want the last item, you need array[array.length - 1], which is verbose and error-prone.
With at(), you write array.at(index). It accepts both positive and negative indices. Negative numbers count backward from the end: array.at(-1) gets the last item, array.at(-2) gets the second-to-last, and so on.
When to Use at()
Use at() when:
- You need negative indexing:
items.at(-1)is cleaner thanitems[items.length - 1] - You have dynamic indices: When a variable might be positive or negative,
at()handles both naturally - You're working with return values: If a function returns an index that could be negative,
at()works seamlessly
const items = ['a', 'b', 'c', 'd'];
// Traditional way - awkward for last item
const last = items[items.length - 1]; // 'd'
// Modern way - cleaner
const last = items.at(-1); // 'd'
// With dynamic indices
const position = -2; // Could come from calculation
items.at(position); // 'c' - works!
items[position]; // undefined - doesn't work
When Bracket Notation Is Fine
Stick with brackets when you're always using positive indices you know are valid. It's slightly faster and more universally recognized.
Key Takeaway: Use at() when you need negative indexing or dynamic indices that might be negative; use bracket notation for straightforward positive index access where readability isn't hurt.