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
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.
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.
String.fromCharCode() performs the reverse type of conversion.
console.log(String.fromCharCode(80)); // P
console.log(String.fromCharCode(81)); // Q
const text = "ABC";
console.log(text.charCodeAt(99)); // NaN
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 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.”
NaN for invalid indexes.charCodeAt() alone for characters represented by surrogate pairs.For related case conversion, see toLowerCase().
String Reference String.fromCharCode()
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.