#53: charAt(5) vs at(-1)
Topic: strings · Difficulty: ★★
const s = 'hi';
console.log(JSON.stringify(s.charAt(5)));
console.log(s.at(-1));Output
"" i
Why
charAt(index) is the classic string-indexing method, but it has no concept of negative indices — any out-of-range index, including one far past the string's length like 5 on a 2-character string, just returns the empty string '' (shown here via JSON.stringify to make it visible). The newer at(index) method was added specifically to support negative indices counting from the end: at(-1) means 'the last character', so it returns 'i' from 'hi' directly, something charAt has no way to express at all. at() falls back to undefined for out-of-range indices instead of an empty string.