DEV Community

Discussion on: Get last element of array in JavsScript

Collapse
 
giokhar profile image
Giorgi Kharshiladze

I think you are missing one of the methods that was added not too long ago.
Array.prototype.at(). To get the last element in an array you can do myArr.at(-1).
developer.mozilla.org/en-US/docs/W...

Collapse
 
vickyktk profile image
vickyktk

Oh Yes !!! Thank You. This pretty usefull and easy

Collapse
 
dagropp profile image
Daniel Gropp

While it’s a cool new method, keep in mind that currently it’s not supported in Safari based devices.

Collapse
 
labspl profile image
Wojciech

In Safari Technology Preview you can activate it via Develop > Experimental Features

Collapse
 
lexlohr profile image
Alex Lohr

You can easily polyfill it:

if (![].at) {
  Array.prototype.at = function(pos) { return this.slice(pos, pos + 1)[0] }
}
Enter fullscreen mode Exit fullscreen mode
Thread Thread
 
nbouvrette profile image
Nicolas Bouvrette

This won't work with negative values.