The at() Method in JavaScript
When you want to get a specific element of an array or string, we often use array[index] notation. But when we need to get elements from the end, we start writing lengthy expressions like arr[arr.length - 1].
This is exactly the problem that the at() method solves.
What does at() do?
- Returns an element from an array or string by index
- Supports negative indices for accessing elements from the end
Syntax
array.at(index)
string.at(index)
- index can be positive or negative
- Returns undefined if index is out of bounds
Array Examples
const numbers = [10, 20, 30, 40];
console.log(numbers.at(0)); // 10
console.log(numbers.at(2)); // 30
console.log(numbers.at(-1)); // 40 (last element)
console.log(numbers.at(-2)); // 30
String Examples
const message = "Hello";
console.log(message.at(0)); // H
console.log(message.at(-1)); // o
Key Difference: arr.at(-1) vs arr[arr.length - 1]
const arr = [1, 2, 3];
console.log(arr.at(-1)); // 3
console.log(arr[arr.length - 1]); // 3
Both return the last element, but at() is more readable, concise and simpler.
When to Use at()
- When you need to access the last or nth element from the end
- When you want to write clean and readable code
- When working with strings and needing to get characters from the end