Last Updated : 14 Jul, 2024
The JavaScript Array at() method takes an integer value (index) as a parameter and returns the element of that index. It allows positive and negative integers. For the negative integer, it counts back from the last element in the array.
Syntax:
at(index);
Parameter: This method accepts one parameter that are described below:
Return Value: The element corresponding to the specified index in the array. It returns undefined value if we access index < 0, or index + array.length.
Javascript Array at() Method ExamplesExample 1: This code shows the value extracted at the given index.
JavaScript
const arr = [45, 32, 69, 21];
const index = 3;
console.log(arr.at(index));
Example 2: It will provide a function that returns the last element found in a specified array.
JavaScript
const subjects = ["Maths", "Physics", "Biology", "Chemistry"];
function lastElement(arr) {
return arr.at(-1);
}
const item = lastElement(subjects);
console.log(item);
subjects.push("DSA");
const item2 = lastElement(subjects);
console.log(item2);
Example 3: This code shows the value extracted from the Nested Array.
JavaScript
const arr = [45, [32, 27], 21];
const index = 1;
console.log(arr[1].at(index));
Supported Browsers:
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4