Javascript  New at Method

Javascript New at Method

ยท

2 min read

Hello guys ๐Ÿ˜Ž, Today we are gonna be learning about the new javascript array at method. The at method is one of the new addition to the javascript language. It was added during the es2022 update

Before the es2022 update, the bracket notation was used to fetch specific elements from an array. The at method brings a new and improved way of doing this

const arr = ['sheep','lion','tiger','hen']
console.log(arr[0]);
//OUTPUT
sheep

//USING THE AT METHOD
arr.at(0)//This gives the same output

Although in the case of if u want to perform a backward iteration using the bracket notation i.e negative indexing. In this case, you have to refer to the length of the array. The at method gives us a better and more simplified way of doing it

//Using The bracket notation
const arr = ['sheep','lion','tiger','hen']
console.log(arr[arr.length - 1)])
//Output
hen

//USING THE AT METHOD
console.log(arr.at(-1)) //This gives the same output

Other Important uses of the at method

  • Comparing Methods

The at method helps us to structure and improve the readability of our code when comparing methods

const colors = ['red','blue','white','purple']
//Using the bracket notation
console.log(colors[colors.length - 2])

//using the slice method
console.log(colors.slice(-2,-1))

//Using the at method
console.log(colors.at(-2))

//This all gives 'white' but the at method can easily be understandable

Note:

The slice method returns a shallow copy of an array into a new array object selected from start to end. Start and end represent the indexes of the items to be copied in the array. The original array is not modified

  • Usage on strings

The at method can also be used on strings

console.log('jonas'.at(1))
//Output is j

Advantages of at method

  • The at method is mostly useful in counting from the end of an array or getting the last element and useful for method chaning(Combining multiple methods together)

  • Improves readability

  • No need to use the length property when accesing the negative index

The at method can simply be said to be equivalent to the bracket notation but for negative indexes. To get values quickly from an array,use the bracket notation

So thats it for today,If you have any question please mention it in the comment section below ๐Ÿ˜Š.

ย