JavaScript Array at
Method (Live Playground)
The JavaScript Array at
method allows you to access the elements of an array by their index. One special feature of this method is that it accepts negative integers, with -1
referring to the last element of the array, -2
referring to the second last, and so on.
Here's a basic example:
let numbers = [10, 20, 30, 40, 50];
let result = numbers.at(2);
console.log(result);
// Expected output:
// 30
In the example above, numbers.at(2)
returns the third element of the numbers
array because array indices start at 0.
Live Playground, Try it Yourself
Let's use a negative index:
let numbers = [10, 20, 30, 40, 50];
let result = numbers.at(-1);
console.log(result);
// Expected output:
// 50
Here, numbers.at(-1)
returns the last element of the numbers
array.
Live Playground, Try it Yourself
The at
method provides a convenient way to access elements from the end of an array without having to calculate their positive index.