const - JS | lectureWorking With Arrays

The New at Method

Working With Arrays

There is a new and very simple array method in ES2022 called the at method. To see it in action, let's start by creating some dummy array.

script.js
const array = [55, 94, 11, 23, 64];

Now, if we wanted to take one of the values out of the array, let's say the third value, we would traditionally do this:

script.js
console.log(array[2]); // 11

But now with the new ``at` method, we can do the same thing.

script.js
/**
 * We specifiy the same index , and we get the same value.
*/
console.log(array.at(2)); // 11

So, basically, we are now doing what we say. That is, writing array[2] means array at index 2. Hence that's why this new method is called the at method.

Maybe this doesn't look all too useful. So, what's the big deal here? Well, there is one particularity of the at method which makes it quite useful to use instead of the bracket notation.

Let's say we wanted to get the last element of the array. Assuming that we don't know the length of the array, we would write something like this:

script.js
console.log(array[array.length - 1]); // 64

This is quite a common scenario in JavaScript. And that's why there is another solution using the slice method as we learned in the previous lecture.

script.js
console.log(array.slice(-1)); // [64]
/**
 * Since we need the value and not the array,we need to use
 * the bracket notation at index 0 after the slice method.
*/
console.log(array.slice(-1)[0]); // 64

These are the two more traditional ways of solving the problem of getting the last element. However, as you can probably guess, the new at method makes this process even easier.

script.js
console.log(array.at(-1)); // 64

The question now is, show you use this new at method or should you keep using the bracket notation? Well, as always, it depends. If you want to get the last element of an array, or start counting from the end of an array, then you should probably start using the at method. Also, if you want to do something called method chaining, which we will talk about later, then the at method is perfect for that. On the other hand, if you just want to quickly get a value from an array, like for example the first element, then, of course, you can keep using the bracket notation.

To finish this lecture, I also want to let you know that the at method can also be used on strings.

script.js
console.log('Terry'.at(0)); // T
console.log('Terry'.at(-1)); // y