JavaScript's at method
Details, examples, practice
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.
array.at(index) string.at(index)
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
const message = "Hello"; console.log(message.at(0)); // H console.log(message.at(-1)); // o
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.