The Array.at() method in JavaScript is used to access an element at a specific index in an array. This method provides a more readable and concise way to retrieve elements compared to traditional bracket notation, especially when dealing with negative indices to access elements from the end of the array.
Syntax
array.at( index );
Parameters
Parameter | Description |
---|---|
index | The index of the element to be retrieved. A negative index counts back from the last item in the array. |
Return Value
Return Type | Description |
---|---|
Array Element | Returns the element at the specified index. If the index is out of bounds, it returns undefined . |
Example 1: Accessing an Element at a Positive Index
This code retrieves the element at index 1 from the array arr using the Array.at() method and prints it to the console.
let arr = [10, 20, 30, 40, 50]; console.log("Element at index 1: " + arr.at(1));
Output
Element at index 1: 20
Example 2: Accessing an Element at a Negative Index
This code retrieves the last element from the array arr using a negative index with the Array.at() method and prints it to the console.
let arr = [10, 20, 30, 40, 50]; console.log("Element at index -1: " + arr.at(-1));
Output
Element at index -1: 50
Example 3: Accessing an Element Out of Bounds
This code attempts to retrieve an element at an out-of-bounds index from the array arr using the Array.at() method, resulting in undefined.
let arr = [10, 20, 30, 40, 50]; console.log("Element at index 10: " + arr.at(10));
Output
Element at index 10: undefined
Example 4: Accessing an Element in an Empty Array
This code attempts to retrieve an element from an empty array arr using the Array.at() method, resulting in undefined.
let arr = []; console.log("Element at index 0: " + arr.at(0));
Output
Element at index 0: undefined
Supported Browsers
Chrome | Edge | Firefox | Opera | Safari |
---|---|---|---|---|
92 | 92 | 90 | 78 | 15 |