Skip to content
Tutorials Center
My learning

Topics

JavaScript Reference ยท String

String.prototype.charAt()

Reference for JavaScript String.prototype.charAt(): return the character at a given index, what happens out of range, and how it differs from at() and brackets.

The charAt() method returns a string containing the single UTF-16 code unit at a given zero-based index. If the index is outside the string, it returns an empty string rather than undefined.

It is one of the oldest string methods. Today, bracket notation (str[i]) or at() is used more often, but charAt() is still common in older code and is handy when you want a string result in every case.

JavaScript
"hello".charAt(1); // "e"

Try it

JS Reading characters

Press Run (or Ctrl + Enter) to see the console output here.

No output.

JS charAt() versus brackets and at()

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Syntax

JavaScript
string.charAt(index)
Name Description
index Zero-based position of the character to return. Converted to an integer (fractions are cut off); NaN and a missing argument become 0. Negative numbers are not counted from the end.

Return value: a string of length 1 for a valid index, or an empty string "" if index is below 0 or not less than the string's length.

Exceptions: none.

Usage notes

  • Never undefined. The empty-string result lets you chain string methods safely, for example str.charAt(0).toUpperCase() works even on an empty string.
  • No negative indexing. charAt(-1) returns "". Use at(-1) or charAt(str.length - 1) for the last character.
  • Code units, not characters. For characters outside the Basic Multilingual Plane (most emoji), charAt() returns one half of a surrogate pair. Iterate with for...of or the spread operator to get whole code points.
  • Same as brackets for valid indexes. str.charAt(i) and str[i] return the same value inside the string. They differ only out of range ("" versus undefined).
  • Strings are read-only. You can read with charAt() but not assign: str[0] = "x" silently does nothing (or throws in strict mode).
  • To compare characters, str.charAt(i) === "a" works; for a numeric code use charCodeAt().
  • Generic. String.prototype.charAt.call(value, i) converts the value to a string first, so it works on numbers: String.prototype.charAt.call(123, 1) returns "2".

Browser support

charAt() is a classic method available in every browser and Node.js version.