In JavaScript, accessing the last element of an array is not as straightforward as in other languages. In Python, for example, you can use negative indexing to access the last element of an array. In JavaScript, however, using negative indexing with brackets []
doesn't work. Instead, you have to use brackets with the length of the array minus one.
const frameworks = ['Nuxt', 'Remix', 'SvelteKit', 'Ember'];
// β Doesn't work
frameworks[-1];
// undefined
// β
Works
frameworks[frameworks.length - 1];
// 'Ember'
To make array indexing more flexible, JavaScript introduced the at
method. The at
method allows you to get the element at a given index in an array, with support for negative indexing.
const frameworks = ['Nuxt', 'Remix', 'SvelteKit', 'Ember'];
// π₯ Supports negative indexing
frameworks.at(-1);
// 'Ember'
However, the at
method is only an accessor method. This means that you can't use it to mutate the array. If you want to mutate the array, you have to use the bracket notation.
const frameworks = ['Nuxt', 'Remix', 'SvelteKit', 'Ember'];
// β Doesn't work
frameworks.at(-1) = 'React';
// Uncaught ReferenceError: Invalid left-hand side in assignment
// β
Works
frameworks[frameworks.length - 1] = 'React';
// ['Nuxt', 'Remix', 'SvelteKit', 'React']
A similar method for mutations that does support negative indexing has been introduced as well. The with
method allows you to change the value of an element at a given index in an array. However, it returns a new array with the change, as it doesn't mutate the original array.
const frameworks = ['Nuxt', 'Remix', 'SvelteKit', 'Ember'];
// β
Returns a copy with the change
frameworks.with(-1, 'React');
// ['Nuxt', 'Remix', 'SvelteKit', 'React']
Browser support
The at
function has baseline browser support on since 2022. Node has support in all current LTS versions.
If you're targetting older browsers, a pollyfill is available in core-js.
Chrome | Edge | Firefox | Safari | Node.js |
---|---|---|---|---|
β 92 | β 92 | β 90 | β 15.4 | β 16.6.0 |
The with
function is newer, having only baseline browser support since July 2023. Node includes support since version 20.
Luckily, there is also a polyfill available in core-js.
Chrome | Edge | Firefox | Safari | Node.js |
---|---|---|---|---|
β 110 | β 110 | β 115 | β 16 | β 20.0.0 |
Conclusion
This article introduced the at
method to access elements in an array. It supports negative indexing, which comes in handy when selecting the last elements. The with
method is a new syntax that allows you to change the value of an element at a given index. However, it returns a new array with the change, as it doesn't mutate the original array. Both methods are supported in modern browsers, but you might need a polyfill for older browsers.
Interested in content like this? Follow along on ~Twitter~ X.
Top comments (0)