Skip to content
Tutorials Center
My learning

Topics

JavaScript Reference ยท String

String.prototype.charCodeAt()

Reference for JavaScript String.prototype.charCodeAt(): get the UTF-16 code unit number at an index, handle NaN, and why emoji need codePointAt() instead.

The charCodeAt() method returns the numeric value of the UTF-16 code unit at a given index. The result is an integer between 0 and 65535. For ordinary letters, digits and punctuation this equals the character's Unicode (and ASCII) number: "A".charCodeAt(0) is 65.

If the index is outside the string, the result is NaN. For characters beyond U+FFFF, such as emoji, charCodeAt() sees only one half of a surrogate pair; use codePointAt() for the full code point.

JavaScript
"A".charCodeAt(0); // 65

Try it

JS Character numbers

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

No output.

JS Case checks and surrogate pairs

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

No output.

Syntax

JavaScript
string.charCodeAt(index)
Name Description
index Zero-based position. It is converted to an integer (fractions are cut off); NaN and a missing argument become 0.

Return value: an integer from 0 to 65535, the UTF-16 code unit at index, or NaN if index is negative or not less than the string's length.

Exceptions: none.

Usage notes

  • NaN, not undefined. Out-of-range reads give NaN, which is never equal to itself. Test with Number.isNaN(code), or compare the index with length first.
  • Code units, not code points. For a character above U+FFFF, you get a high surrogate (0xD800 to 0xDBFF) at the first index and a low surrogate (0xDC00 to 0xDFFF) at the next. codePointAt() combines them into one number.
  • Not always ASCII. Values above 127 are non-ASCII characters; values above 255 do not fit in a single byte.
  • Inverse operation. String.fromCharCode() converts the numbers back into characters.
  • Not for sorting by language. Code unit order is not alphabetical order in most languages; use localeCompare() or Intl.Collator.
  • Not a byte count. The number of code units says nothing about UTF-8 byte length; encode with TextEncoder to count bytes.
  • Uses: simple hashes and checksums, character-class checks, and converting letters to numbers (ch.charCodeAt(0) - 97 for a to z).

Browser support

charCodeAt() is a classic method that works in every browser and Node.js version.