paint-brush
Introducing the at() Method for JavaScript Arraysby@imsabir
334 reads
334 reads

Introducing the at() Method for JavaScript Arrays

by MohammedMarch 7th, 2022
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

ECMA2022 brings a new method for us i.e., at(index), you can get the element at the provided index. This method can be used for getting any index value. For example, if you do fruits.at(-1) then it will give you the last element of fruit. with the normal array, the method it's not possible to do.
featured image - Introducing the at() Method for JavaScript Arrays
Mohammed HackerNoon profile picture



What is ES2022?

For those who don’t know, ES2022 OR EcmaScript 2022 is standard for scripting developed with the cooperation of Netscape and Microsoft and mainly derived from Netscape's JavaScript, the widely-used scripting language that is used in Web pages to affect how they look or behave for the user.


It’s abbreviated to ES1, ES2, ES3, ES5, and ES6. Since 2016 new versions are named by year (ECMAScript 2016 / 2017 / 2018).


const fruits = ['apple','banana','mango','custard'];


Now, let say we want to access the last element of fruits array, but what if you don't know length of array.


How will you do that?

Well, there are different approaches to achieve this:


  1. Using length property of array:


let lastElement = fruits[fruits.length - 1]; console.log(lastElement );


  1. Using the slice() method:


let lastElement = fruits.slice(-1);console.log(lastElement );

  1. Using the pop() method:


let lastElement = fruits.pop();console.log(lastElement);

But if you look into this method, this method’s main objective is not to output the last element of the array but we are manipulating it in such a way that it gives the last element of an array. Also, sometimes, they are performance issues. see here


So, ECMA2022 brings a new method for us i.e., at(index).


With at(index), you can get the element at the providedindex.
See example below


 console.log(fruits.at(1));  // apple
 console.log(fruits.at(-1)); // custard
 console.log(fruits.at(2)); // mango

Working jsfiddle is here :


Interestingly if you do fruits.at(-0) it gives you apple.


So, merry go round.

Cheers!


First Published here