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:
- index – This method accepts a single parameter that holds the index of the array element. The index may have positive or negative, if it is negative then it gives from the last index elements.
Return value: This method returns the character at the specified index. The index starts from 0.
Example 1:
Javascript
// array const array1 = [45, 46, 47, 48, 49] console.log(array1.at(-1)); console.log(array1.at(1)); |
Output:
49 45
Example 2:
Javascript
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:
- Improves readability of code as we do not need to specify array_name repeatedly.
- No need to use the length property to access the negative index.
Supported Browsers:
- Chrome 38 and above
- Edge 12 and above
- Firefox 24 and above
- Opera 25 and above
- Safari 8 and above