DEV Community

Cover image for Array Indexing Method
Shubham Battoo
Shubham Battoo

Posted on • Originally published at shubhambattoo.in

Array Indexing Method

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

Top comments (2)

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

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.