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
Arrays: In JavaScript, an array is a single variable that is used to store different elements. It is often used when we want to store a list of elements and access them by a single variable. Unlike most languages where the array is a reference to the multiple variables, in JavaScript, the array is a single variable that stores multiple elements.
// Initializing while declaring var houseNumbers = [101, 102, 103, 104, 105];
Why 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 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.
at(index): This method returns the character at the specified index. String in JavaScript has zero-based indexing.
Parameters: 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.
Example 1:
Javascript
<script> // array const array1 = [45, 46, 47, 48, 49] console.log(array1.at(-1)); console.log(array1.at(1)); </script> |
Output:
49 45
Example 2:
Javascript
<script> const strarr = [ "apple" , "ball" , "cow" , "dog" , "elephant" , "fish" ]; console.log(strarr.at(-1)); console.log(strarr.at(-3)); </script> |
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.