charAt() returns the UTF-16 code unit at a zero-based position in a string as a one-character string. If the index is outside the string, it returns an empty string.
const text = "Hello World";
console.log(text.charAt(4)); // o
string.charAt(index)
The first character is index 0. A missing index is treated as 0.
This preserves the positions demonstrated on the original page.
const str = "Hello World";
console.log(str.charAt(3)); // l
console.log(str.charAt(4)); // o
console.log(str.charAt(5)); // space
console.log(str.charAt(6)); // W
console.log(str.charAt(20)); // ""
console.log(str.charAt(-2)); // ""
const text = "Welcome";
console.log(text.charAt(3)); // c
console.log(text[3]); // c
The main difference appears out of range: charAt() returns "", while bracket access returns undefined.
at() is convenient when you want to count backward from the end with a negative index.
const text = "JavaScript";
console.log(text.at(-1)); // t
console.log(text.charAt(-1)); // ""
const word = "ABC";
for (let i = 0; i < word.length; i++) {
console.log(word.charAt(i));
}
See the for loop tutorial for loop syntax and control flow.
charAt() works in UTF-16 code units. A character outside the Basic Multilingual Plane can use two positions, so charAt() can return only one surrogate half. Use codePointAt() with String.fromCodePoint(), or iterate the string with for...of, when full Unicode code points matter.
const symbol = "😀";
console.log(symbol.length); // 2 UTF-16 code units
console.log([...symbol][0]); // 😀
Character-by-character access is one way to understand a string reverse algorithm, although spread syntax is safer for many Unicode code points than indexing by UTF-16 unit.
at() for that behavior.undefined; charAt() returns an empty string.String Reference Lowercase Strings
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.