How to Use the at() Method in JavaScript Arrays and Strings
The
at() method in JavaScript lets you get an element from an array or string by its index, supporting negative numbers to count from the end. Use it like array.at(index) or string.at(index) to access elements safely.Syntax
The at() method is called on an array or string and takes a single integer argument representing the index of the element you want to access.
- Positive index: Counts from the start (0 is the first element).
- Negative index: Counts backward from the end (-1 is the last element).
javascript
array.at(index) string.at(index)
Example
This example shows how to use at() with an array and a string, including accessing elements from the end using negative indexes.
javascript
const fruits = ['apple', 'banana', 'cherry', 'date']; const word = 'hello'; console.log(fruits.at(1)); // banana console.log(fruits.at(-1)); // date console.log(word.at(0)); // h console.log(word.at(-2)); // l
Output
banana
date
h
l
Common Pitfalls
Some common mistakes when using at() include:
- Using an index out of range returns
undefinedinstead of an error. - Older browsers may not support
at(), so check compatibility or use polyfills. - Confusing negative indexes with positive ones; negative indexes count from the end.
javascript
const arr = [10, 20, 30]; // Wrong: expecting error but gets undefined console.log(arr.at(5)); // undefined // Correct: check if result is undefined const value = arr.at(5); if (value === undefined) { console.log('Index out of range'); }
Output
undefined
Index out of range
Quick Reference
| Usage | Description |
|---|---|
| array.at(index) | Returns element at index, supports negative indexes. |
| string.at(index) | Returns character at index, supports negative indexes. |
| Negative index | Counts from the end (-1 is last element). |
| Out of range | Returns undefined if index is invalid. |
Key Takeaways
Use
at() to access array or string elements by index, including negative indexes.Negative indexes count backward from the end, making it easy to get last elements.
If the index is out of range,
at() returns undefined instead of throwing an error.Check browser compatibility before using
at() in older environments.Use
at() for cleaner and safer element access compared to bracket notation.