The at() method of the Array class in JavaScript returns the array item at the given index. It accepts negative integers, which count back from the last item in the array.
The syntax of Array.at() method is:
at(index)
This at() method of Array returns the array item at the given index. Accepts negative integers, which count back from the last item.
Parameter | Optional/Required | Description |
---|---|---|
index | required | The index of the item to retrieve. Negative integers count back from the last item in the array. |
Array.at() returns value of type Any
.
In JavaScript, we can use the at() method to retrieve an item at a specific index in an array.
For example,
const arr = [10, 20, 30, 40, 50];
const itemAtIndex2 = arr.at(2);
console.log(itemAtIndex2);
30
In JavaScript, we can use at() method to get the last item in the array using index = -1.
For example,
const arr = ['apple', 'banana', 'cherry'];
const lastItem = arr.at(-1);
console.log(lastItem);
cherry
In JavaScript, we can use at() method to get the first item in the array using index = 0.
For example,
const arr = [true, false, true, false];
const firstItem = arr.at(0);
console.log(firstItem);
true
In this JavaScript tutorial, we learned about at() method of Array: the syntax and few working examples with output and detailed explanation for each example.