Back to Blog
JavaScriptArraysat()ES2022

JavaScript Array at() Method Guide

Master the JavaScript Array at() method for accessing elements with positive and negative indices.

B
Bootspring Team
Engineering
December 13, 2019
6 min read

The at() method returns the element at a given index, supporting negative indices for accessing from the end. Here's how to use it.

Basic Usage

Loading code block...

Comparison with Bracket Notation

Loading code block...

Working with Strings

Loading code block...

TypedArrays

Loading code block...

Practical Examples

Loading code block...

Array Slicing Patterns

Loading code block...

Method Chaining

Loading code block...

Safe Access Pattern

Loading code block...

Pagination Helper

Loading code block...

Ring Buffer

Loading code block...

Best Practices

Usage: ✓ Use for negative indexing ✓ Cleaner than length - n ✓ Works on strings too ✓ Safe for method chaining Benefits: ✓ More readable code ✓ Consistent with other languages ✓ Works with TypedArrays ✓ Returns undefined for out of bounds Patterns: ✓ Get last element: arr.at(-1) ✓ Get second to last: arr.at(-2) ✓ Safe access with fallback ✓ Method chaining Avoid: ✗ Using when you need the index ✗ Forgetting undefined return ✗ Overcomplicating simple access ✗ Using with very old browsers

Conclusion

The at() method provides a clean syntax for accessing array elements with negative indices. Use it to get elements from the end without calculating length - n. It works on arrays, strings, and TypedArrays, and returns undefined for out-of-bounds access rather than throwing an error.

Share this article

Help spread the word about Bootspring

Related articles