Course contentsShow
← JavaScript
Lesson 1994 of 2,72341. Modern JavaScript Features (ES2020+)Free lesson

at() on Strings and Typed Arrays

Explore how at() works uniformly across arrays, strings, and typed arrays for consistent negative indexing everywhere.

at() on Strings and Typed Arrays

You'll learn how the at() method works consistently across arrays, strings, and typed arrays, giving you uniform negative indexing everywhere.

The Uniform Interface

While we've explored at() on arrays, its true power is consistency. The same at() syntax works identically on strings and typed arrays (like Uint8Array, Int32Array, etc.), giving you one mental model for accessing indexed elements with negative positions.

at() on Strings

Strings support at() just like arrays, making character access cleaner:

const greeting = "Hello";

// Positive indexing
console.log(greeting.at(0));   // "H"
console.log(greeting.at(1));   // "e"

// Negative indexing
console.log(greeting.at(-1));  // "o" (last character)
console.log(greeting.at(-2));  // "l" (second to last)

// Compare to bracket notation
console.log(greeting[greeting.length - 1]);  // "o" (verbose!)

at() on Typed Arrays

Typed arrays, which store numeric data efficiently, also support at():

const bytes = new Uint8Array([10, 20, 30, 40, 50]);

console.log(bytes.at(0));   // 10
console.log(bytes.at(-1));  // 50 (last byte)
console.log(bytes.at(-2));  // 40

const ints = new Int32Array([100, 200, 300]);
console.log(ints.at(-1));   // 300

Why This Matters

You now have one pattern for accessing the last element of any indexed collection: collection.at(-1). Whether it's an array, string, or typed array, the syntax is identical and readable.

Key Takeaway: The at() method provides uniform negative indexing across arrays, strings, and typed arrays, creating a consistent interface for accessing elements from the end of any indexed collection.