Open In App

ES2022 JavaScript at() Method

Before getting into at() method we should know about what arrays, strings and Typed array in JavaScript is and also how to access arrays

JavaScript at() Method: Now, usually we access array elements via their indexes, and we know that the array index starts from 0.  Now if we want to access the 102 value form above the house number array we can easily retrieve it with index = 1 which is a positive index. Now we want to access the last element of the array we cannot specify directly -1 as before ES22 the negative indexing was not supported so what we need to do is write an array name specify the length function and then do -1 e.g. array_name.length-1 but after ES22 release negative index supports indexable classes.



Basically, at() methods are used to access elements of an array by specifying or passing negative indexing.

Syntax:



anyVar.at(index);

Parameters: 

Return value: This method returns the character at the specified index. The index starts from 0.

Example 1: 




// array
const array1 = [45, 46, 47, 48, 49]
console.log(array1.at(-1));
console.log(array1.at(1));

Output: 

49
45

Example 2: 




const strarr = ["apple","ball", "cow", "dog"
"elephant", "fish" ];
console.log(strarr.at(-1));
console.log(strarr.at(-3));

Output : 

fish 
dog

Advantages of using at() method:

Supported Browsers:

Article Tags :