Array.at()
The Array.at()
method in JavaScript is used to access elements of an array using both positive and negative indices.
Syntax
array.at(index)
Parameters
Parameter | Description |
---|---|
index | A number representing the position of the element to access. It can be positive (from the start) or negative (from the end). |
Return Value
at() method returns the element in the array matching the given index.
If given index is out of bounds for the array, then the method returns undefined
.
Examples
1. Accessing Elements of Array with Positive Indices
This example demonstrates how to retrieve elements using positive indices. The at()
method accesses elements from the start of the array.
const numbers = [10, 20, 30, 40, 50];
console.log(numbers.at(0));
console.log(numbers.at(2));
Output
10
30
numbers.at(0)
returns element at index=0 in thenumbers
array.numbers.at(2)
returns element at index=2 in thenumbers
array.
2. Accessing Elements with Negative Indices
Negative indices allow you to access elements from the end of the array. The index -1
refers to the last element. The index -3
refers to the third element from the end.
const numbers = [10, 20, 30, 40, 50];
console.log(numbers.at(-1));
console.log(numbers.at(-3));
Output
50
30
3. Accessing Elements Beyond the Bounds
When the index
is out of range, the at()
method returns undefined
. This avoids runtime errors.
const numbers = [10, 20, 30, 40, 50];
// 10th element from beginning
console.log(numbers.at(10));
// Sixth element from end towards left
console.log(numbers.at(-6));
Output
undefined
undefined
4. Using at()
in a Function
The at()
method can be used to build utility functions, such as retrieving the last element of an array.
function getLastElement(arr) {
return arr.at(-1);
}
const fruits = ["apple", "banana", "cherry"];
console.log(getLastElement(fruits));
Output
cherry
5. Comparing at()
with Bracket Notation
This example highlights the difference between at()
and traditional bracket notation, particularly for accessing the last element of an array.
// Example: Comparing at() with bracket notation
const numbers = [10, 20, 30, 40, 50];
// Using bracket notation
console.log(numbers[numbers.length - 1]);
// Using at()
console.log(numbers.at(-1));
Output
50
50