Skip to content
Related Articles
Get the best out of our app
GFG App
Open App
geeksforgeeks
Browser
Continue

Related Articles

Javascript Array at() Method

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

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:

  • index: This parameter specifies the array index of the element. The negative index value counts back from the end of array.

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.

Example 1: This code shows the value extracted at the given index.

Javascript




<script>
    const arr = [45, 32, 69, 21];
    const index = 3;
 
    console.log(arr.at(index));
</script>


Output

21

Example 2: It will provide a function that returns the last element found in a specified array.

Javascript




<script>
    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);
</script>


Output

Chemistry
DSA

Supported Browsers:

  • Google Chrome 92
  • Edge 92
  • Firefox 90
  • Opera 78
  • Safari 15.4
My Personal Notes arrow_drop_up
Last Updated : 01 Mar, 2023
Like Article
Save Article
Similar Reads
Related Tutorials