JavaScript2 min read
Array.at() - Negative Indexing in JavaScript
Access array elements from the end without length calculations. Clean and readable
S
Shahar Amir
The Problem
Getting the last element of an array is ugly:
javascript
12345
const items = ['a', 'b', 'c', 'd', 'e'];
// The old wayconst last = items[items.length - 1]; // 'e'const secondLast = items[items.length - 2]; // 'd'The Solution: Array.at()
javascript
123456
const items = ['a', 'b', 'c', 'd', 'e'];
// Clean and readableconst last = items.at(-1); // 'e'const secondLast = items.at(-2); // 'd'const first = items.at(0); // 'a'Negative indices count from the end. That's it.
Real Examples
javascript
123456789101112
// Get last item in a listconst users = await fetchUsers();const newest = users.at(-1);
// Get file extensionconst parts = filename.split('.');const ext = parts.at(-1);
// Circular array accessfunction getItem(arr, index) { return arr.at(index % arr.length);}Works on Strings Too
javascript
12345
const str = 'Hello';
str.at(0); // 'H'str.at(-1); // 'o'str.at(-2); // 'l'vs Bracket Notation
| Feature | `arr[i]` | `arr.at(i)` |
|---|---|---|
| Positive index | ✅ | ✅ |
| Negative index | ❌ | ✅ |
| Returns undefined if out of bounds | ✅ | ✅ |
Browser Support
Available in all modern browsers and Node.js 16.6+.
No polyfill needed in 2024+. Just use it.
#arrays#es2022#methods#clean-code
Stay Updated 📬
Get the latest tips and tutorials delivered to your inbox. No spam, unsubscribe anytime.