Grian

Grian

Using the new .at() method in JavaScript

Note: This syntax, as of now, is not supported by TypeScript, see the status of that in this PR

The .at() method is a new method introduced in V8 9.2, It is available on Array, String and TypedArray's.

This is a method meant to solve the problem of a .last property not existing.

Using this method

Usually, to get the last element of an array-like in JS, you'd do this arr[arr.length - 1], but using this new method, you can do arr.at(-1).

You might be familiar with this syntax from Python, as in python you can do arr[-1] and get the same element.

This method can also work as a way to index an array-like using arr.at(2) which is equivalent to arr[2]

Compatibility

At the time of writing, this method is supported by Chrome 92, Firefox 90, their mobile equivalents and Deno 1.12.0. Node does not yet support this method.

The TC39 Proposal also provides a simple polyfill, available here.

Relevant links and documentation