November 15, 2021 08:06 pm GMT
Original Link: https://dev.to/josec/javascript-new-array-method-at-3aip
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 Potter`, `Star Wars`];const oldWay = movies[movies.length - 1];console.log(`The last movie is ${oldWay}`); // Star Warsconst 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.
You can find more information at Mozilla MDN
Original Link: https://dev.to/josec/javascript-new-array-method-at-3aip
Share this article:
Tweet
View Full Article
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To