// 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.
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.
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.