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

18

u/senocular Oct 26 '21

Because fruits[-1] won't give you "avacado", it will give you undefined

-15

u/Gibbo3771 Oct 26 '21

fruits[fruits.length - 1]

This is what people mean, no one expects [-1] to work.

29

u/senocular Oct 26 '21

at() reduces the requirement to refer to your array twice. This can be useful when you're using it at the end of a longer expression.

fruits.map(toBarcode).filter(onSale).at(-1)

4

u/yadoya Oct 27 '21

The real tip is always in the comments