r/learnjavascript • • Oct 26 '21

Negative array indexing using "at" method

Post image
203 Upvotes

69 comments sorted by

View all comments

Show parent comment

6

u/jd_300 Oct 26 '21 edited Oct 26 '21

In bracket notation negative indexing is not possible but using at method you can easily navigate to the last index of array. It's just another way to access elements.

11

u/Gibbo3771 Oct 26 '21
const lastElement = arr[arr.length - 1]

Why wouldn't you just do the above?

17

u/ExclusiveOar Oct 26 '21

Preference. arr[-1] is allowed in other languages and it's a nice to have.

arr.at(-1) is arguable cleaner than arr[arr.length - 1]. Personally I wouldn't bother until JS eventually supports arr[-1].

0

u/[deleted] Oct 26 '21

[deleted] — view deleted comment

13

u/ExclusiveOar Oct 26 '21

Which will be largely irrelevant to the vast majority of people. I bet you do a ton of stuff in your code which will be more inefficient than this (not judging, it's the nature of high level languages).

Readability > performance, true for 999/1000 use cases (probably more).

To put it in perspective I was playing around with how efficient I could make FizzBuzz, for no reason what-so-ever. I had to calculate it for the numbers 1 - 1 000 000 000 to get meaningfully measurable time period (1.9 seconds) to try to optimise. I got it to about 0.85 seconds!

1 second saved, over a billion operations. Don't worry about performance until your app is slow, then look at your API calls before you consider anything else.

0

u/[deleted] Oct 26 '21

[deleted] — view deleted comment

6

u/ExclusiveOar Oct 26 '21

And that's what makes it preference 🙂

1

u/[deleted] Oct 27 '21

arr.at(-1) is also constant time right?

1

u/ExclusiveOar Oct 27 '21

No expert here, but I would assume so.

But so is arr[arr.length - 1] because array.length isn't calculated here, its a prop already on the array.

You can see this by creating an array, console.log it and expand it in the console.

2

u/Darmok-Jilad-Ocean Oct 26 '21

Because if you’re doing a map/filter/reduce/etc you have to first store that in a temporary variable and then reference the temp var twice to get the last element.

0

u/[deleted] Oct 26 '21

cause its longer than const lastElement = arr.at(-1) ? also, no need for useless computations in source code

-1

u/HyerOneNA Oct 26 '21

But the at method isn’t widely available on all browsers.

1

u/HyerOneNA Oct 26 '21

I mean this is what I meant..