javascript – New array method at()

The new array method at() allows us to get access to array indexes using both positive as negative indexes.

This way we don’t need to do maths anytime we want to access to the last array element.

const movies = [`Terminator 2`, `Rambo`, `Harry Pott…


This content originally appeared on DEV Community and was authored by Jose

The new array method at() allows us to get access to array indexes using both positive as negative indexes.

This way we don't need to do maths anytime we want to access to the last array element.

const movies = [`Terminator 2`, `Rambo`, `Harry Potter`, `Star Wars`];

const oldWay = movies[movies.length - 1];
console.log(`The last movie is ${oldWay}`); // Star Wars

const newWay = movies.at(-1);
console.log(`The last movie is ${newWay}`); // Star Wars

It's not just for the last element:

console.log(`First movie ${movies.at(0)}`); // Terminator 2

If we pass an index that not exists it will return Undefined.

At this time the array method at() it's not compatible with all the browsers yet so for use it on production you will need a polyfill.

Image description

You can find more information at Mozilla MDN


This content originally appeared on DEV Community and was authored by Jose


Print Share Comment Cite Upload Translate Updates
APA

Jose | Sciencx (2021-11-15T20:06:20+00:00) javascript – New array method at(). Retrieved from https://www.scien.cx/2021/11/15/javascript-new-array-method-at/

MLA
" » javascript – New array method at()." Jose | Sciencx - Monday November 15, 2021, https://www.scien.cx/2021/11/15/javascript-new-array-method-at/
HARVARD
Jose | Sciencx Monday November 15, 2021 » javascript – New array method at()., viewed ,<https://www.scien.cx/2021/11/15/javascript-new-array-method-at/>
VANCOUVER
Jose | Sciencx - » javascript – New array method at(). [Internet]. [Accessed ]. Available from: https://www.scien.cx/2021/11/15/javascript-new-array-method-at/
CHICAGO
" » javascript – New array method at()." Jose | Sciencx - Accessed . https://www.scien.cx/2021/11/15/javascript-new-array-method-at/
IEEE
" » javascript – New array method at()." Jose | Sciencx [Online]. Available: https://www.scien.cx/2021/11/15/javascript-new-array-method-at/. [Accessed: ]
rf:citation
» javascript – New array method at() | Jose | Sciencx | https://www.scien.cx/2021/11/15/javascript-new-array-method-at/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.