How to Use array.at() in JavaScript: Syntax and Examples
The
array.at(index) method in JavaScript returns the element at the given index. It supports negative indices to count from the end, making it easier to access elements like the last item with array.at(-1).Syntax
The array.at(index) method takes one argument:
- index: A number representing the position of the element to retrieve. Positive numbers count from the start (0-based), and negative numbers count from the end (-1 is the last element).
This method returns the element at the specified position or undefined if the index is out of range.
javascript
array.at(index)
Example
This example shows how to use array.at() to get elements by positive and negative indices.
javascript
const fruits = ['apple', 'banana', 'cherry', 'date']; console.log(fruits.at(1)); // banana console.log(fruits.at(-1)); // date console.log(fruits.at(10)); // undefined
Output
banana
date
undefined
Common Pitfalls
Common mistakes when using array.at() include:
- Using negative indices with older methods like
array[index], which do not support negatives. - Expecting
array.at()to modify the array (it only reads elements). - Not handling
undefinedwhen the index is out of range.
Always check if the returned value is undefined before using it.
javascript
const numbers = [10, 20, 30]; // Wrong: negative index with bracket notation console.log(numbers[-1]); // undefined (does NOT get last element) // Right: use .at() for negative index console.log(numbers.at(-1)); // 30
Output
undefined
30
Quick Reference
| Feature | Description |
|---|---|
| Parameter | A single integer index (positive or negative) |
| Positive index | Counts from start (0 is first element) |
| Negative index | Counts from end (-1 is last element) |
| Return value | Element at index or undefined if out of range |
| Supported since | ECMAScript 2022 (ES13) |
Key Takeaways
Use
array.at(index) to access elements by positive or negative index safely.Negative indices count from the end, making it easy to get last elements like
array.at(-1).Bracket notation
array[index] does not support negative indices.Always check for
undefined when the index might be out of range.The
at() method is part of modern JavaScript (ES2022) and improves code readability.