The JavaScript string.charAt() method
The charAt() method returns the character at a given index in a string. "hello".charAt(1) is "e". It's similar to bracket notation str[1], with one difference: an out-of-range index returns an empty string "" rather than undefined.
Overview
charAt() reads a single character from a string by its zero-based index. "world".charAt(0) is "w". It's one of the oldest string methods and does almost exactly what bracket access (str[0]) does today.
The one practical difference is the out-of-range case. charAt() returns an empty string ("") when the index doesn't exist, whereas str[index] returns undefined. Depending on what you do next, that distinction can matter — an empty string is still a string, while undefined is not.
In modern code, bracket notation (str[i]) is the common way to read a character, and slice() or the newer at() (which supports negative indices) cover most needs. charAt() remains perfectly valid and is often seen in the capitalize-first-letter idiom: s.charAt(0).toUpperCase() + s.slice(1). For the numeric character code rather than the character itself, use charCodeAt() or codePointAt().
Syntax
str.charAt(index)
"hello".charAt(0) // "h"
"hello".charAt(10) // "" (empty string, not undefined)
Parameters
The string.charAt() method accepts the following parameters.
| Parameter | Description |
|---|---|
index |
The zero-based position of the character to return. Defaults to 0. |
Example
<pre id="out" style="font:15px ui-monospace,monospace"></pre>
<script>
const word = 'javascript';
const capitalized = word.charAt(0).toUpperCase() + word.slice(1);
document.getElementById('out').textContent =
'first char: ' + word.charAt(0) + '\n' +
'capitalized: ' + capitalized; // first char: j / capitalized: Javascript
</script>
Best practices
- Use it (or bracket notation) to read a single character by index.
- Remember an out-of-range index returns
"", notundefined. - The capitalize idiom is handy:
s.charAt(0).toUpperCase() + s.slice(1). - For the numeric code of a character, use
charCodeAt()orcodePointAt().
Frequently asked questions
What is the difference between charAt() and bracket notation?
charAt() returns an empty string, while str[index] returns undefined.How do I capitalize the first letter of a string?
s.charAt(0).toUpperCase() + s.slice(1).How do I get the last character of a string?
str.at(-1), or str.charAt(str.length - 1).What does charAt() return if the index is out of range?
"".