Array.prototype.at()
what is .at() method in JavaScript?
const myList = ['index0', 'index1', 'index2']
myList.at(1) // 'index1'
mylist.at(-1) // 'index2'
there are many methods in js that similarly do this, why using this new method?
Array.prototype.at()
what is .at() method in JavaScript?
const myList = ['index0', 'index1', 'index2']
myList.at(1) // 'index1'
mylist.at(-1) // 'index2'
there are many methods in js that similarly do this, why using this new method?
Yes, there are similar ways to get an element from an array or string, but at() will use a clear and easy syntax to get this.
give an index and return value
the principle is easy, just put your desire index and get value, if there isn't a value at this index, it returns undefined
for examples:
const myList = ['index0', 'index1', 'index2']
// to get latest item in the list using common ways:
const latestItem = myList[ myList.length - 1]
// using simpler approach with at()
const latestItem = myList.at(-1)
similarly, at() method will work fine with strings.