Hacker News new | ask | show | jobs
by almost 1886 days ago
It’s not adding negative indexes, a negative number will index from the end.

So [0, 1, 2, 3].at(-2) === 2

1 comments

That would mean getting the last element of the array would be [0,1,2,3].at(-1).

I don't like that very much.

Mind you, I don't like the idea of using [0,1,2,3].at(-0) either...

Don’t think of it as counting from the end of the array — think of it as counting in reverse from the 0th element. .at(1) gets the next element (index 1) while .at(-1) loops around and gets the “previous” element (index 3, in this case).

Or, if it’s more intuitive, you can think of the array index as an unsigned integer where the max is equal to the length of the array. If you try to assign -1 to a uint8, the result will be 255 — the highest possible value (the last index).

Good thing we don't have to stagnate progress just because what we have will never be perfect.