The Array.at()
method is a built-in JavaScript function that allows you to access elements in an array using their index. Its ability to handle negative indices, making it easier to retrieve elements from the end of an array.
Syntax
arr.at(index);
Parameters
Parameter | Description |
---|---|
index | The index of the element to be accessed. A negative value counts backward from the end of the array. |
Return Value
The Array.at()
method returns the element at the specified index, if it exists. undefined
if the index is out of bounds.
Example 1: Accessing Elements by Index – The Array.at() is used to access elements at specific positions in the array.
let arr = [10, 20, 30, 40, 50]; console.log(arr.at(0)); // Output: 10 console.log(arr.at(2)); // Output: 30
Example 2: Using Negative Indexes – Negative indices retrieve elements from the end of the array.
let arr = [10, 20, 30, 40, 50]; console.log(arr.at(-1)); // Output: 50 (Last element) console.log(arr.at(-3)); // Output: 30 (Third-to-last element)
Example 3: Handling Out-of-Bounds Indices – When the index is out of bounds, Array.at() returns undefined.
let arr = [10, 20, 30, 40, 50]; console.log(arr.at(6)); // Output: undefined console.log(fruits.at(-8)); // Output: undefined
Example 4: The at() method works seamlessly with strings, allowing you to access characters by positive or negative index.
let str = 'hello'; console.log(str.at(0)); // Output: 'h' console.log(str.at(-1)); // Output: 'o'
Example 5: This example shows how Array.at() simplifies accessing the first or last element of an array.
let arr = [10, 20, 30, 40, 50]; // Access the last element let lastElement = arr.at(-1); console.log(lastElement); // Output: 50 // Access the first element let firstElement = arr.at(0); console.log(firstElement); // Output: 10
Example 6: Comparison with Bracket Notation
let arr = [10, 20, 30, 40, 50]; console.log(arr[arr.length - 1]); // Output: 50 (Traditional way) console.log(arr.at(-1)); // Output: 50 (Using at())
Supported Browsers
Browser | Support |
---|---|
Chrome | 92+ |
Firefox | 90+ |
Safari | 15.4+ |
Edge | 92+ |
Opera | 78+ |
Internet Explorer | Not supported |