JavaScript - 27

JavaScript - 27: Password Generator

Create a simple practice password generator using letters and numbers.

Your challenge: Let the user choose a length from 8 to 20, then build a random password of that length.

✦ JavaScript Editor
▶ Live Output

Build the password

The chars string contains all the letters and numbers the generator can choose from.

Use a for loop that runs once for each character in the requested password length.

Inside the loop: Math.floor(Math.random() * chars.length) creates a random character position.

Check the length

Use an if statement to make sure the number is between 8 and 20.

If it is outside that range, show a message and use return to stop the function.

Display the result

Call generatePassword(length) and place the returned password inside the display with textContent.

Try it: Generate passwords with lengths of 8, 12, and 20.

Note: This generator uses Math.random() for practice. Real password generators should use a cryptographically secure random source.

👀 Show Solution
const generateBtn = document.getElementById("generate");
const passwordDisplay = document.getElementById("password");
const lengthInput = document.getElementById("length");

function generatePassword(length) {
  const chars =
    "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

  let password = "";

  for (let i = 0; i < length; i++) {
    const randomIndex = Math.floor(Math.random() * chars.length);
    password += chars[randomIndex];
  }

  return password;
}

generateBtn.addEventListener("click", function() {
  const length = Number(lengthInput.value);

  if (length < 8 || length > 20) {
    passwordDisplay.textContent = "Please choose between 8 and 20.";
    return;
  }

  passwordDisplay.textContent = generatePassword(length);
});

The loop chooses one random character at a time until the password reaches the requested length.