We know how to access array items using their index, like scores[0]
for the first item.
Engagement Message
But what if you wanted to get the very last item in an array without having to calculate its length?
Modern JavaScript has a handy method for this: .at()
. The .at()
method lets you access items from the beginning, just like square brackets, but it also accepts negative numbers to count from the end.
To get the last item, you simply use -1
.
Engagement Message
Does this seem like a useful shortcut?
So, if we have
using planets.at(-1)
would give you "Earth"
.
This works no matter how many items are in the array. .at(-1)
is always the last one.
Engagement Message
What would colors.at(-1)
give you if colors = ["red", "green", "blue"]
?
Following this pattern, .at(-2)
refers to the second-to-last item, refers to the third-to-last item, and so on.
