The at() method, introduced in ES2022, allows you to access elements of arrays, characters of strings, and elements of typed arrays using positive or negative indexes.
- Positive indexes access elements from the beginning, starting at 0.
- Negative indexes access elements from the end, with -1 referring to the last element.
- It eliminates the need to use the length property to access the last elements.
- It returns undefined when the specified index is out of range for an array.
Syntax:
array.at(index);Parameter:
- - index: The zero-based index of the element to retrieve. A negative index counts backward from the end.
Return value: Returns the element at the specified index. For strings, it returns a string containing the character at that position. If the index is out of range, it returns undefined.
Example 1: Using at() with an Array
const array1 = [45, 46, 47, 48, 49];
console.log(array1.at(-1));
console.log(array1.at(1));
Output
49 46
In this example, at(-1) returns the last element, while at(1) returns the element at index 1.
Example 2: Accessing Elements from the End
const strarr = ["apple", "ball", "cow", "dog", "elephant", "fish"];
console.log(strarr.at(-1));
console.log(strarr.at(-3));
Output
fish dog
Here, at(-1) returns the last element ("fish"), and at(-3) returns the third element from the end ("dog").
Advantages of the at() Method
- Improves readability when accessing elements from the end of an array.
- Eliminates the need to calculate indexes using array.length - 1.
- Provides a consistent way to access elements in arrays, strings, and typed arrays.