r/learnjavascript • • Oct 26 '21

Negative array indexing using "at" method

Post image
203 Upvotes

69 comments sorted by

View all comments

28

u/HyerOneNA Oct 26 '21

Why use the at method when you can just use square bracket notation?

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

16

u/VikaashHarichandran Oct 26 '21

People coming from other scripting languages do expect

7

u/[deleted] Oct 26 '21

wouldnt it be nice to have though?

19

u/greymalik Oct 26 '21

People coming from Python or Ruby expect it.

-13

u/doyouseewhateyesee Oct 26 '21

people coming from python or ruby should read the docs

2

u/Mad-chuska Oct 26 '21

Also true

2

u/[deleted] Oct 26 '21

No idea why you're getting downvoted. When I'm switching to a different language I should learn differences not expect it to behave the same. After all if it would work exactly the same what would be the point of switching.

0

u/doyouseewhateyesee Oct 26 '21 edited Oct 26 '21

lol right. i’m not going to pick up python and start writing javascript methods

it’s comical that a comment recommending devs to read the docs in a learnjavascript subreddit is being downvoted. or don’t read the docs I guess, not my problem