#programming
#javascript
#web development

Creating a Random Letter Generator Using Javscript

Anonymous

AnonymousOct 04, 2023

Creating a Random Letter Generator Using Javscript

Source Code

<!DOCTYPE html >
  <html>
    <head>
      <title>Random Letter Generator</title>
    </head>
    <body>
      <h1>Random Letter Generator</h1>
      <button id="generateButton">Generate Random Letter</button>
      <p id="randomLetter"></p>
      <script>
        function generateRandomLetter() {
             const alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
             const randomIndex = Math.floor(Math.random() * alphabet.length);
             const randomLetter = alphabet.charAt(randomIndex);
             document.getElementById("randomLetter").textContent = randomLetter;
        }
        document.getElementById("generateButton").addEventListener("click", generateRandomLetter);
      </script>
    </body>
  </html>

Ouput 1:

Run the code in your browser and get the result same as given in the below screenshot:

Ouput 2:

Click on this Generate Random Letter button, and this will generate a random letter for you.

Explanation in detial:

Step 1:

const alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

Defines a constant variable alphabet that contains all uppercase letters of the alphabet.

Step 2:

const randomIndex = Math.floor(Math.random() * alphabet.length);

Generates a random number between 0 and the length of the alphabet array (26 in this case), then rounds it down to the nearest whole number using Math.floor(). This random number will be used as an index to select a random letter from the alphabet.

Step 3:

const randomLetter = alphabet.charAt(randomIndex);

Retrieves the random letter from the alphabet array using the random index.

Step 4:

document.getElementById("randomLetter").textContent = randomLetter;

Display the random letter on the page

Happy Coding !