create a password with a custom length and uppercase letters in javascript

index.tsx
function generatePassword(length) {
    const uppercaseLetters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    let password = "";
    for (let i = 0; i < length; i++) {
        let randomIndex = Math.floor(Math.random() * uppercaseLetters.length);
        password += uppercaseLetters[randomIndex];
    }
    return password;
}

console.log(generatePassword(8)); // Example output: "ZKRXJBSF"
381 chars
12 lines

Explanation:

  • The function generatePassword takes a parameter length which is the desired length of the password.
  • The string uppercaseLetters contains all uppercase letters of the English alphabet.
  • The variable password is initially an empty string to which random uppercase letters will be added.
  • The for loop runs length number of times, generating a random index value between 0 and the length of uppercaseLetters. This random index is used to select a random uppercase letter from the string which is added to password.
  • Once the loop finishes, password contains the generated password of the desired length with only uppercase letters.
  • The generated password is returned by the function.

gistlibby LogSnag