This post will discuss how to convert a character to its ASCII code in JavaScript.

For example, the ACSII code of 'A' is 65, '0' is 48, 'a' is 97, etc.

1. Using String.charCodeAt() function

The charCodeAt() method returns UTF-16 code unit at the specified index. This returns an integer between 0 and 65535. The first 128 Unicode code points (0 to 127) match the ASCII character set.

The following example returns the Unicode value for 'A', which is 65.

Download  Run Code

 
To get the reverse, you can use the fromCharCode() method, which returns a string from a specified sequence of code points.

Download  Run Code

2. Using String.codePointAt() function

The codePointAt() method returns a number representing the code point value of the character at the given index. The following code returns the Unicode value for 'a', which is 97.

Download  Run Code

 
It is different from the charCodeAt() method as it can handle code point which cannot be represented in a single UTF-16 code unit (i.e., characters greater than 0xFFFF).

Download  Run Code

 
To do the reverse, you can use the fromCodePoint() method, which returns a string created using the specified sequence of code points.

Download  Run Code

That’s all about converting a character to its ASCII code in JavaScript.