Getting the last item of an array (the elegant way)

Getting the last item of an array (the elegant way)

Recognize that unpleasant feeling of a potential panic attack when you need to get the last item of an array in JS?

theArray[theArray.length -1]

Thought so. Totally verbose and unsexy.

Sure, pop() can be used, but that will alter the array, which is probably not what you intended.

Another option is to go with ['๐ŸŠ','๐Ÿ','๐Ÿผ'].slice(-1), but that will actually return that last item as a new array. In this example the result will be ['๐Ÿผ']. So to get the actual value, slice(-1)[0] is needed.

Fair enough, but something is still nagging. We can do better.

In a perfect world we should be able to: theArray[-1].

This is sadly not the case, but ECMAScript 2021 introduces a lovely little gem. Let me introduce: The array method at().

The at() method takes an integer value and returns the item at that index, allowing for positive and negative integers. Negative integers count back from the last item in the array.

So that means we can just do theArray.at(-1)

Nice!

The not so nice part is that browser support is pretty good but not great, with the usual suspect Safari only supporting it in their TP (Technology preview). But weโ€™re getting there.

In NodeJS you can safely use it from Version 16.6.0, which was released this summer.

So there you have it - The ugly way, the acceptable way, and the elegant (but maybe still not ready to use) way, of getting the last item of an array.