DEV Community

Discussion on: Tips: How to get last element of an array in javascipt

Collapse
 
miketalbot profile image
Mike Talbot ⭐
   const arr = [1, 2, 3]
   const lastElement = arr.at(-1)
Enter fullscreen mode Exit fullscreen mode
Collapse
 
jonrandy profile image
Jon Randy 🎖️

Beat me to it

Collapse
 
mrcaidev profile image
mrcaidev

I especially love this feature when combined with optional chain, in TypeScript, e.g. unknownArr?.at(1) ?? 0. It makes the code so much cleaner.

Collapse
 
quocbahuynh profile image
Quoc Huynh Website

perfect

Collapse
 
muhammed_navas profile image
MUHAMMED NAVAS

it is making an error, arr.at is not a function.

Collapse
 
miketalbot profile image
Mike Talbot ⭐ • Edited

This is modern ES6 syntax, you will either need a modern browser/version of node or to use a transpiler like Babel.

This is the currently supported list:

caniuse.com/mdn-javascript_builtin...

Some comments have been hidden by the post's author - find out more