JavaScript charCodeAt(): Get UTF-16 Code Units

charCodeAt() returns the numeric UTF-16 code unit at a zero-based string index. For basic Latin letters, the returned value also matches the familiar ASCII value.

const text = "FBA";
console.log(text.charCodeAt(0)); // 70

charCodeAt() Syntax and Return Value Top ↑

string.charCodeAt(index)

The return value is an integer from 0 to 65535 for a valid UTF-16 code unit. An invalid index produces NaN.

Read the UTF-16 Value of Every String Position Top ↑

This modernizes the original PQRS loop example.

const str = "PQRS";
for (let i = 0; i < str.length; i++) {
  console.log(str.charCodeAt(i));
}
80
81
82
83

The length property provides the upper bound, and the for loop walks through each index.

Convert UTF-16 Code Units Back to Characters Top ↑

String.fromCharCode() performs the reverse type of conversion.

console.log(String.fromCharCode(80)); // P
console.log(String.fromCharCode(81)); // Q

Out-of-Range Indexes Return NaN Top ↑

const text = "ABC";
console.log(text.charCodeAt(99)); // NaN

charCodeAt() vs codePointAt() Top ↑

charCodeAt() returns one UTF-16 code unit. Some Unicode characters use a surrogate pair, so use codePointAt() when you need the full Unicode code point that starts at an index.

const symbol = "😀";
console.log(symbol.charCodeAt(0));  // first surrogate code unit
console.log(symbol.codePointAt(0)); // 128512

ASCII Values and JavaScript UTF-16 Top ↑

ASCII occupies code values 0–127, and those values map directly within Unicode/UTF-16. That is why examples such as "A".charCodeAt(0) return 65. But JavaScript strings are not limited to ASCII, so describe charCodeAt() as a UTF-16 code-unit method rather than an “ASCII converter.”

Common charCodeAt() Mistakes Top ↑

  • Calling the result a Unicode code point in every case; it is one UTF-16 code unit.
  • Forgetting indexes start at 0.
  • Ignoring NaN for invalid indexes.
  • Using charCodeAt() alone for characters represented by surrogate pairs.

For related case conversion, see toLowerCase().

String Reference String.fromCharCode()




Subscribe to our YouTube Channel here



plus2net.com










✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer