Apps Artificial Intelligence CSS DevOps Go JavaScript Laravel Linux MongoDB MySQL PHP Python Rust Svelte Vue

Access JavaScript Array Elements with `at()`

1 min read .
Access JavaScript Array Elements with `at()`

Array.prototype.at() returns the element at a given integer index. Its main advantage over bracket notation is support for negative indexes.

Positive Indexes

const fruits = ['apple', 'banana', 'cherry'];

console.log(fruits.at(0)); // 'apple'
console.log(fruits.at(1)); // 'banana'

Negative Indexes

console.log(fruits.at(-1)); // 'cherry'
console.log(fruits.at(-2)); // 'banana'

Without at(), the traditional equivalent for the last element is:

fruits[fruits.length - 1]

Out-of-Range Access

console.log(fruits.at(99));  // undefined
console.log(fruits.at(-99)); // undefined

It Also Works on Strings and Typed Arrays

The at() method is available on strings and typed arrays as well:

console.log('hello'.at(-1)); // 'o'

Conclusion

Use at() when negative indexing makes access clearer, especially for the last or second-to-last element. Bracket notation remains perfectly fine for ordinary non-negative indexes.

Related Posts

chevron-up