Wednesday, 23 July 2025

JavaScript now has negative indexing... sort of

Searching arrays in JavaScript (or any language, really) can be a tricky proposition. One of my favorite ways to search for a value within an array in JavaScript, is the indexOf() method.

With this method, I just need to invoke it while passing in the string to search for, as an argument.
var arr = ["This", "is", "a", "test", "array"];
var index = arr.indexOf("test"); // 3

But what if I wanted it the other way round? What if I wanted to find out what value was the, say, third element in an array? Well, simple enough.
var arr = ["This", "is", "a", "test", "array"];
var val = arr[2]; // "a"

Now, what if I wanted the second last element in the array?

In Ruby, one could do this. This is known as negative indexing.
arr = Array["This", "is", "a", "test", "array"]
val = arr[-2] // "test"

In JavaScript, this doesn't fly. Get the length of the array, less 2, then use it as the index.
var arr = ["This", "is", "a", "test", "array"];
var val = arr[arr.length - 2]; // "test"

There is a way to use negative indexing in JavaScript, though. Use the slice() method.
var arr = ["This", "is", "a", "test", "array"];
var val = arr[-2, -2]; // ["test"]

The end result is an array, though. So there's one more step to take before you can access the value.
var arr = ["This", "is", "a", "test", "array"];
var val = arr[-2, -2]; // ["test"]
val = val[0]; // "test"


So, those are the things you have to do, in order to get the value of an element n times from the end... or do you? Now with the at() method, you literally just need to do this.
var arr = ["This", "is", "a", "test", "array"];
var val = arr.at(-2); // "test"

What is this sorcery?!

The at() method was introduced as recently as 2023. With it, a programmer can do in JavaScript what one can do in Python and Ruby - use negative indexes. Is that really so important considering that functionally, we already had all we needed in the slice() method?

slice(), slice(), baby.

Well, the slice() method complicates things. Sure, it's a handy method that can be used for big or small cases, but for the case we're talking about, it's complete overkill. Using the at() method makes code a lot more readable, and the importance of that cannot be understated.

Conclusion

It's always fun to see how programming languages evolve. Would have been nice for me to discover the at() method sooner than years after it emerged, but this only goes to underscore the fact that things change so fast in this industry and there's often something new to learn.

["Thanks", "for", "reading", "and", "see", "you", "again!"],
T___T

No comments:

Post a Comment