The Recent at() Method in JavaScript
Tags: javascript, atmethod, javascriptmethods
Published: 2023-11-03 13:41:59

**The Cool Way to Dial Elements in JavaScript** 📞 😎

Python devs, hold the smirks! JavaScripters, rejoice! Our syntax is catching up, and coding just got a tiny bit easier!

A concise, elegant syntax has been introduced for accessing elements from the end of an array or string. Meet the .at() method! 🎉

Before we dive into some of the details, here’s a quick example:

```
let arr = [1, 2, 3, 4];

arr.at(-1) -> 4
```

This feature has long been requested by developers, as it can simplify coding and make the syntax more intuitive, similar to languages like Python. Initially, the proposed name was .item(), but due to web incompatibility issues and potential conflicts with existing properties and methods in different libraries, .at() seems to be a better alternative.

Let's explore it!
<br>

## In a world without at() 😔

Before at(), accessing elements from the end of arrays or strings involved cumbersome syntax or performance drawbacks.

**array.length**
The prevalent method was `arr[arr.length - N]`, where N is the Nth item from the end, and `arr.length – N` gives the index position to access the N-th element from the end.

Let's look at an example!

```
let arr = [10, 20, 30, 40, 50];

arr.length -> 5
```

To get the 2nd element from the end (40 in this case), we subtract 2 from 5 (the length of the array), so `arr[arr.length - 2]` is equivalent to `arr[3]` :

```
arr[arr.length - 2]  // Output: 40
```

Notice how this approach, while functional, requires using the name of the array twice. It then adds 7 more characters due to `.length`. It is also incompatible with anonymous values. If a function returns an array, we first have to store it in a temporary variable before we can grab one of its values. Too much effort for a developer in 2023!

**slice()**
While it is compatible with anonymous values, `slice()` is less optimal: it creates a temporary array that is immediately discarded after retrieving a given element. 

```
let arr = [1, 2, 3, 4, 5];

arr.slice(-2)[0] -> 4

// happening behind the scene
// arr.slice(-2) -> [4, 5]
```
Notice how it also requires the use of the square brackets to access an element of the resultant array? Too much work!
<br>

## Why not just use [ ]? 🤔
The `[]` syntax in JavaScript is a universal one, applicable to all objects, and not exclusive to arrays and strings. When we refer to a value using an index, such as `arr[3]`, we are essentially referring to the property of the object with the key "3", a feature applicable to any object.

Using `arr[-1]` in the current JavaScript environment will not output an error. JavaScript will be looking for the property with the key "-1", and not for an index counting backward from the end. If it does not find it, the output will be undefined.
<br>

## How does at() work? ⚙️
The `.at()` method takes an index as its parameter and returns the element in the array corresponding to the given index. This index is zero-based and is converted to an integer.

Let's start with an array:

```
let arr = [10, 20, 30, 40, 50];
```

and loop through every possible case!
<br>

✅ Given a positive index, `at()` behaves just like the square bracket notation:

```
arr[2] -> 30

arr.at(2) -> 30
```
In this case, the `[]` syntax is probably better, since it's shorter.
<br>

✅ An index equal to or greater than the array length is out of the range for the given array, and the method will return `undefined`:

```
arr.at(5) -> undefined
```

<br>✅ Given a negative index, `at()` will count back from the end of the array:

```
arr.at(-2) -> 40

// index + array.length = -2 + 5 = 3

arr[3] -> 40
```
Notice how the accessed index will be equivalent to "index + array.length"!

<br>✅ An index that is less than the negative value of the array length is also out of the range:

```
arr.at(-6) // Output: undefined
```
The method will not attempt to access any property, and it will return `undefined`.
<br>

## All is GOOD with the world now! 😊

So, there we have it, the new .at() method, making array and string manipulation more intuitive and clean!

Now we can effortlessly dial in the index we want, be it from the start or the end, and JavaScript will connect us to our element without any fuss!

Who's laughing now, Python? 😜
<br>

## References
[MDN Documentation on the at() method](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/at)

[GitHub repository for the TC39 proposal to add the .at() method to the JavaScript language](https://github.com/tc39/proposal-relative-indexing-method)

<br>Blog post originally published September 22, 2023 on corinamurg.dev.

Credit: Photo by [Wesley Hilario](https://unsplash.com/@wesley_squared) on [Unsplash](https://unsplash.com/photos/person-holding-black-rotary-telephone-CNSH-JGEwtI)