JavaScript charCodeAt method, to be used on strings, takes an index as an optional parameter. This method returns the Unicode character of the corresponding character specified by the index.

So the syntax is as follows: string.charCodeAt(index).

If the index is not specified, it will have a default value of 0.

Recall that Unicode is an encoding that assigns a unique number to each alphanumeric character. This encoding is independent of the language used.

For more information, see the following link: unicode encoding.

JavaScript charCodeAt

In this first example we will get the Unicode of the first character of a string.

So here’s a possible implementation of the JavaScript charCodeAt method:

var sentence = 'do coding creativo';
var character = sentence.charCodeAt(0);

So, in the browser console, we get the value 102, which is the corresponding Unicode character of the letter f.

Using the JavaScript charCodeAt method in the last character of a string

In this example we get the Unicode encoding of the last character of a string taken as input.

To do this, it is necessary to use the length property on the string which, remember, returns the number of characters of a given string.

Here is the complete example:

var sentence = 'do coding creativo';
var character = sentence.charCodeAt(sentence.length-1);

In this case, the value 101 is obtained, which corresponds to the Unicode encoding of the letter o.

If we try to obtain the Unicode encoding of an index that does not exist then we will have the value NaN (Not a Number).


In this lesson we have seen some practical examples on using the JavaScript charCodeAt method, in the next lessons we will see many other examples with other methods on strings and arrays.

Some useful links

JavaScript tutorial

JavaScript Calculator

Object in JavaScript

For in loop

Caesar cipher decoder

Slot Machine in JavaScript

Introduction to JavaScript language

Learn JavaScript – basic concepts

JavaScript variables and costants