The shortest code to access the last array item.
Sometimes I have to access the last element in an array.
The most typical case is when I need to visualize series of different kinds of overlapping events as time spans. To convert a series into a span I have to determine the times of the first and last event in a series. For that I sort the array representing a series and then take the date of the first and last element in the array.
const events = [1590000000000, 1580000000000, 1600000000000];events.sort();const start = events[0];
const stop = events[events.length - 1];
To access the last element in the array I used the expression:
events[events.length — 1]
It looks cumbersome because the same array is referred to twice. Such an expression contrasts with most of the modern JavaScript, which is quite concise and to the point. JavaScript would be even more neat if arrays could be indexed from the end like it is possible in Python using negative indexes events[-1]
. Alternatively, Array
could have a method returning the last element without changing the array like it does getLast()
method of LinkedList
class in Java.