Skip to content

Instantly share code, notes, and snippets.

@Cema2019
Last active August 5, 2025 16:41
Show Gist options
  • Select an option

  • Save Cema2019/292c92a0eb2ca041db97db6b0123dac5 to your computer and use it in GitHub Desktop.

Select an option

Save Cema2019/292c92a0eb2ca041db97db6b0123dac5 to your computer and use it in GitHub Desktop.
JS code to generate a password.

Build a basic password generator that meets the following requirements:

  1. Minimum length of 8 characters.
  2. Must include at least:
    • One uppercase letter (A–Z)
    • One lowercase letter (a–z)
    • One number (0–9)
    • One symbol (e.g., !@#$%^&*)
  3. The result must be random every time the password is generated.
  4. Display the generated password in the console or on screen.
function generatePassword() {
const upperChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
const lowerChars = "abcdefghijklmnopqrstuvwxyz";
const numbers = "0123456789";
const symbols = "!@#$%^&*()";
const allChars = upperChars + lowerChars + numbers + symbols;
// Variable length from 8 to 12 characters
const length = Math.floor(Math.random() * 5) + 8;
// Helper function to get a random character from a string
const getRandom = (str) => str[Math.floor(Math.random() * str.length)];
// Get at least one of each required characters
let password = [
getRandom(upperChars),
getRandom(lowerChars),
getRandom(numbers),
getRandom(symbols),
];
// Fill array with remaining characters to fit length
password = password.concat(
Array.from({ length: length - password.length }, () => getRandom(allChars))
);
// Shuffle characters in password array
password.sort(() => Math.random() - 0.5);
const finalPassword = password.join("");
console.log(finalPassword);
return finalPassword;
}
generatePassword();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment