References

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

The JavaScript string.charCodeAt() method

Method JavaScript All modern browsers Updated
Quick answer

The charCodeAt() method returns the numeric UTF-16 code of the character at a given index. "A".charCodeAt(0) is 65. To go the other way — number to character — use String.fromCharCode(). For characters outside the basic range (like emoji), use codePointAt() instead.

Overview

charCodeAt() gives you the number behind a character — its UTF-16 code unit. "A".charCodeAt(0) returns 65, "a" is 97, and so on. It's how you work with characters numerically: checking ranges (is this a digit, an uppercase letter?), simple ciphers, or sorting by code.

Its inverse is the static String.fromCharCode(), which turns a code back into a character: String.fromCharCode(65) is "A". The two together let you shift characters around — adding 1 to a letter's code and converting back gives the next letter, the basis of a Caesar cipher.

One limitation to know: charCodeAt() returns a single 16-bit code unit, which can't represent characters above the basic plane — emoji and some scripts are stored as two units (a surrogate pair), so charCodeAt() only sees half of one. For full Unicode code points, use codePointAt() (and String.fromCodePoint() to reverse it), which handle the full range correctly.

Syntax

str.charCodeAt(index)

"A".charCodeAt(0)          // 65
String.fromCharCode(65)    // "A"  (the inverse)
"hi".codePointAt(0)        // 104 (full Unicode)

Parameters

The string.charCodeAt() method accepts the following parameters.

Parameter Description
index The position of the character whose code you want. Defaults to 0.

Example

Live example
<pre id="out" style="font:15px ui-monospace,monospace"></pre>
<script>
  const ch = 'A';

  const code = ch.charCodeAt(0);
  const next = String.fromCharCode(code + 1);

  document.getElementById('out').textContent =
    ch + ' = ' + code + '\n' +
    'next letter: ' + next; // A = 65 / next letter: B
</script>

Best practices

  • Pair it with String.fromCharCode() to convert codes back into characters.
  • Use it for numeric character work — range checks, simple ciphers, code-based sorting.
  • For emoji and characters above the basic plane, use codePointAt() instead.
  • Out-of-range indices return NaN, so validate the index if it's untrusted.

Frequently asked questions

What does charCodeAt() return?
The numeric UTF-16 code of the character at the given index, e.g. "A".charCodeAt(0) is 65.
How do I convert a character code back to a character?
Use String.fromCharCode(code) — the inverse of charCodeAt().
What is the difference between charCodeAt() and codePointAt()?
charCodeAt() returns one 16-bit code unit; codePointAt() returns the full Unicode code point, which is needed for emoji and characters above the basic plane.
What does charCodeAt() return for an invalid index?
NaN.