r/learnjavascript • • Oct 26 '21

Negative array indexing using "at" method

Post image
203 Upvotes

69 comments sorted by

View all comments

Show parent comments

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].

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.