Many programming languages like Python, Ruby, etc
have the ability to do ‘negative indexing’
we can access the elements of the array from the end
by specifying the negative index.
 syntax is used for accessing array and object.
obj refers to accessing the value of key
obj[-1] refers to accessing the value of key
instead of returning the last property of an object.
Many approaches(accessing the
were taken to work around this problem.
at() method was introduced in ECMAScript 2022
and the long-standing request from programmers was answered.
Suppose we have an array sorted in ascending order. We want to get the greatest number in the sorted array.
- One way to get the greatest number is by accessing
Similarly, we can get the ‘N’th greatest element as below -
Using this method adds some inconvenience -
- We need to store the array in a variable.
- We need to use the array name repeatedly
- It is hostile to anonymous values.
If the array name is large, syntax affects the readability.
The other way is to use
.slice()already supports negative indexes so it matches our requirement.
This method avoids some of the drawbacks of using
- Avoids name repetition.
- Friendly to anonymous values.
However, the syntax of using
is a little weird, especially
ECMAScript 2022 adds
at() method in Array, String, and TypedArray.
The index of the array element which needs be be accessed. The ‘index’ parameter supports relative indexing from the end of the array when passed a negative index.
The element in the array that matches the given index.
undefined if the index is not found.
To know more about the details check out the TC39 at() proposal.