DEV Community

loading...
Cover image for Array Indexing Method

Array Indexing Method

shubhambattoo profile image Shubham Battoo Originally published at shubhambattoo.in ・1 min read

Recently, came across a cool Twitter thread which talks about a new way to access the array items.

Basically, this is a tc39 proposal which is at stage 3 at the moment. The at method supports relative indexing from the end, this is a prototype of built-in indexable objects: Array, String, and TypedArrays objects.

You can provide either positive or negative integers both and it will return the item at that index. Negative indexes helping to count back in the array.

const arr = [1, 2, 3, 4, 5];

// Current way to get last item
arr[arr.length - 1]; // 5

// Proposed way
arr.at(-1); // 5
Enter fullscreen mode Exit fullscreen mode

Earlier, there was another proposal which suggested adding a method Array.prototype.last to get the last item from an array. Which did not cross the stage 1.

Currently, it is not supported in any browser but hopefully will be supported soon.

Would love to know what other uses do you guys feel we can have with this method.

Further Reading

Discussion (2)

pic
Editor guide
Collapse
learnwithdrona profile image
Drona

This is good Shubham. Why JS cannot support Pythonic approach to have negative numbers within indexing square brackets.

Collapse
shubhambattoo profile image
Shubham Battoo Author

Thats already there, if you do something like.

arr[-1] ; // undefined
Enter fullscreen mode Exit fullscreen mode

That is why they are not going with that approach.