How to Use charCodeAt in JavaScript: Syntax and Examples
Use the
charCodeAt(index) method on a string to get the Unicode number of the character at the given index. The index starts at 0 for the first character. If the index is out of range, it returns NaN.Syntax
The charCodeAt() method is called on a string and takes one argument:
- index: The position of the character in the string (starting from 0).
It returns a number representing the UTF-16 code unit of the character at that position.
javascript
string.charCodeAt(index)
Example
This example shows how to get the Unicode code of the first character in a string and the third character.
javascript
const text = 'Hello'; const firstCharCode = text.charCodeAt(0); // 'H' const thirdCharCode = text.charCodeAt(2); // 'l' console.log(firstCharCode); console.log(thirdCharCode);
Output
72
108
Common Pitfalls
- Using an index that is negative or greater than or equal to the string length returns
NaN. - Remember that
charCodeAt()returns a number, not the character itself. - For characters outside the Basic Multilingual Plane (like some emojis),
charCodeAt()returns the code of the first part of the surrogate pair, which may be confusing.
javascript
const str = 'Hi'; console.log(str.charCodeAt(5)); // NaN because index 5 is out of range // Correct usage: console.log(str.charCodeAt(1)); // 105 (Unicode for 'i')
Output
NaN
105
Quick Reference
| Method | Description | Example | Output |
|---|---|---|---|
| charCodeAt(index) | Returns UTF-16 code unit of character at index | 'A'.charCodeAt(0) | 65 |
| charCodeAt(index) | Returns NaN if index out of range | 'A'.charCodeAt(5) | NaN |
Key Takeaways
Use charCodeAt(index) to get the Unicode number of a character at a specific position in a string.
Index starts at 0; out-of-range indexes return NaN.
charCodeAt returns a number, not the character itself.
For some special characters like emojis, charCodeAt may return part of a surrogate pair.