Random letter generation using JavaScript
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.
|
1 2 3 4 5 6 7 8 |
function randomUppercaseLetter() { const min = 65; // ASCII code of A const max = 90; // ASCII code of Z const randomCode = Math.floor(Math.random() * (max - min + 1)) + min; return String.fromCharCode(randomCode); } console.log(randomUppercaseLetter()); |
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.
|
1 2 3 4 5 6 7 8 |
function randomLetter() { const letters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; const randomNum = Math.floor(Math.random() * letters.length); const randomLetter = letters.charAt(randomNum); return randomLetter; } console.log(randomLetter()); |
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
function randomLowercaseLetter() { const min = 97; // ASCII code of a const max = 122; // ASCII code of z // create an array of 1 element const randomArray = new Uint8Array(1); // fill the array with random values crypto.getRandomValues(randomArray); // map the value to the range [min, max] const randomCode = randomArray[0] % (max - min + 1) + min; return String.fromCharCode(randomCode); } console.log(randomLowercaseLetter()); |
That’s all about generating a random letter in JavaScript.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)