This post will discuss how to generate a random letter in JavaScript.

1. Using Math.random() and Math.floor() functions

The Math.random() function returns a pseudo-random floating number between 0 (inclusive) and 1 (exclusive), and the Math.floor() function rounds down a specified value to an integer. We can use these functions to generate a random number between the ASCII codes of the required letters and then convert the random number into a letter using the String.fromCharCode() function. For example, the following code will generate a random letter from 'A' to 'Z'. To generate random lowercase characters or numbers, we can modify the range below.

Download  Run Code

2. Using predefined set of characters

Another alternative is to construct a string containing the predefined set of characters for choosing the random letter from. Then we can use Math.random() and Math.floor() to generate a random number between 0 and the length of that string, like we did before. Finally, get the corresponding letter at that index from the string using the String.charAt() method. To illustrate, the following code generates a random letter using a string of the ASCII lowercase and uppercase letters.

Download  Run Code

3. Using Crypto.getRandomValues() function

Finally, we can use the Crypto.getRandomValues() function to get the cryptographically strong random values. It takes an array as a parameter, and fills it with the secure random numbers. For example, the following code will generate a random lowercase letter from 'a' to 'z', using this function.

Download Code

That’s all about generating a random letter in JavaScript.