References

Beginner-friendly references for web development, with live, editable examples.

The JavaScript string.charAt() method

Method JavaScript All modern browsers Updated
Quick answer

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

Live 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 "", not undefined.
  • The capitalize idiom is handy: s.charAt(0).toUpperCase() + s.slice(1).
  • For the numeric code of a character, use charCodeAt() or codePointAt().

Frequently asked questions

What is the difference between charAt() and bracket notation?
They both return the character at an index. The difference is out of range: charAt() returns an empty string, while str[index] returns undefined.
How do I capitalize the first letter of a string?
Combine the parts: s.charAt(0).toUpperCase() + s.slice(1).
How do I get the last character of a string?
Use str.at(-1), or str.charAt(str.length - 1).
What does charAt() return if the index is out of range?
An empty string "".