DEV Community

Aykut Akgün
Aykut Akgün

Posted on

The best way to get the last element of an array:

EDIT: Safari does not support it ,_,
But use it in Node js or with a bundler!

So some people would say:

array[array.length-1]
Enter fullscreen mode Exit fullscreen mode

But I'd say:

array.at(-1)
Enter fullscreen mode Exit fullscreen mode

The Performance of both is the same.

MDN article: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/at

Top comments (2)

Collapse
 
joelbonetr profile image
JoelBonetR 🥇 • Edited

Yes it works in Safari, check the browser compatibility

Array.at has been "recently" introduced into the core API of JavaScript, the purpose is to get better readability and to facilitate getting Array positions starting from the end:

const colors = ['red', 'green', 'blue'];

colors[colors.length-2] // green

colors.at(-2) // green
Enter fullscreen mode Exit fullscreen mode

However if you're getting specific positions forwards is not that fancy:

const colors = ['red', 'green', 'blue'];

colors[1] // green

colors.at(1) // green

// or

for (let i = 0; i < colors.length; i++) {
   console.log( colors[i] );
   console.log( colors.at(i) );
}
Enter fullscreen mode Exit fullscreen mode

Best regards!

Collapse
 
declanmidd profile image
Declan Middleton

Nice, very cool :)