Before the arrival of Array.at() method, JavaScript developers have used many and different ways to return items from an array but there was still need to use negative indexing to get the last item. Array[0] will return the first item but to return the last item you would use Array[ Array.length - 1 ] as described below;
const names = [ 'Billy', 'Tony', 'Peter', 'Timothy', 'Andrew']
const getFirstName = names[0]
console.log(getFirstName) // Billy
const getLastName = names[names.length - 1]
console.log(getLastName) // Andrew
This has been one of the ways to achieve this. You can also do this with other methods like pop, slice and splice. See below;
// pop
const names = [ 'Billy', 'Tony', 'Peter', 'Timothy', 'Andrew']
const getLastName = names.pop()
console.log(getLastName) // Andrew
// slice
const names = [ 'Billy', 'Tony', 'Peter', 'Timothy', 'Andrew']
const getLastName = names.slice(-1)
console.log(getLastName) // ['Andrew']
// splice
const names = [ 'Billy', 'Tony', 'Peter', 'Timothy', 'Andrew']
const getLastName = names.splice(-1)
console.log(getLastName) // ['Andrew']
All the above methods returns the last item but one thing to note; the splice method modifies the array unlike the others. That means it overwrites the original array and returns a new array after the splice method has been performed.
// splice
const names = [ 'Billy', 'Tony', 'Peter', 'Timothy', 'Andrew']
const getLastName = names.splice(-1)
console.log(getLastName) // ['Andrew']
console.log(names) // [ 'Billy', 'Tony', 'Peter', 'Timothy' ]
Using Array.at() method
Array.at() method makes it very easy to return the last item. With the Array.at(), you can now easily get the last item using negative indexing. This method takes an integer value and returns the item at that index, allowing for positive and negative integers.
const names = [ 'Billy', 'Tony', 'Peter', 'Timothy', 'Andrew']
const getLastName = names.at(-1)
console.log(getLastName) // Andrew
const names = [ 'Billy', 'Tony', 'Peter', 'Timothy', 'Andrew']
const getSecondLastName = names.at(-2)
console.log(getSecondLastName) // Timothy
const names = [ 'Billy', 'Tony', 'Peter', 'Timothy', 'Andrew']
const getFirstName = names.at(0)
console.log(getFirstName) // Billy
Array.at() method also works on strings too
const myName = 'Chimezie Innocent'
const getFirstLetter = myName.at(0)
console.log(getFirstLetter) // C
const myName = 'Chimezie Innocent'
const getLastLetter = myName.at(-1)
console.log(getLastLetter) // t
Top comments (0)