DEV Community

Angelo 👨🏾‍💻
Angelo 👨🏾‍💻

Posted on

How to create a Password Generator using JavaScript

Image description

Are you tired of using the same old boring passwords? Look no further, because with our interactive password generator, you can now create a unique and secure password tailored to your specific needs.

First, let’s set the scene. Imagine you’re standing in front of a giant vault, ready to lock away all of your precious online accounts. But, oh no! You realize that you don’t have the key, also known as a strong password.
Don’t fret, because our password generator is here to save the day.

Upon running the code, you’ll be greeted with an exciting welcome message, “Welcome to the web’s safest password generator.

alert(“Welcome to web’s safest password generator”)// Welcome alert
Enter fullscreen mode Exit fullscreen mode

Next, our trusty code will prompt you to choose the length of your desired password. But beware, the vault has strict rules and only accepts passwords between 10 and 64 characters.

// Function to prompt user for password options
function getPasswordOptions() {

  i = 0
  while (i < 1) {
// while loop to include break property in case of non-accepted input

passwordLength = prompt("How many characters-long do you want your password to be?")

if (passwordLength < 10 || passwordLength > 64 || passwordLength % 1 !== 0) {
  alert("You have to choose a number between 10 and 64. Please try again.")
  break;
};
Enter fullscreen mode Exit fullscreen mode

The prompt only accepts numbers and they have to be between 10 and 64, thanks to ||, any incorrect input will break.


Now it’s time to customize the combination of your password. Do you want to include lowercase letters? Uppercase letters? Numbers? Special characters? Our code will guide you through each step, ensuring that your password has the perfect balance of characters.

 lowerCaseCharacters = confirm("Do you want include lower-case characters in your password?")
  upperCaseCharacters = confirm("Do you want include upper-case characters in your password?")
  numberCharacters = confirm("Do you want include numbers in your password?")
  oddCharacters = confirm("Do you want include special characters in your password?")
// Type of characters confirm notifications

  if (lowerCaseCharacters === false &&
      upperCaseCharacters === false &&
      numberCharacters === false &&
      oddCharacters === false) {
        alert("You have to choose at least one type of character to make-up the password. Please try again.")
        break;
      };
// Non-accepted conditions for type of characters where it breaks to start again
  I++ 
  }
}
Enter fullscreen mode Exit fullscreen mode

These lines of code uses the JavaScript confirm() method to display a dialog box with a question “Do you want include lower-case characters in your password?”.
The user can then click “OK” or “Cancel” to confirm or deny the inclusion of lowercase characters in their password. The value returned from this confirm() method is then stored in the variable lowerCaseCharacters.
Rinse and repeat for subsequent arrays.


The code then checks to make sure that the user has selected at least one type of character to include in their password
But that’s not all, our code goes above and beyond to keep your password extra secure. It randomly shuffles the characters in each array to increase the randomness of your password.

It’s like spinning the dials on a safe, but without the risk of getting locked out.

// Function for getting a random element from an array
function getRandom(arr) {
  let allArrays = []; //included allArrays locally (instead of globally) so we don't have to reload the page to generate another password
  i = 0
  while (i < 1) {
//randomizes arrays
                     specialCharacters.sort(() => Math.random() - 0.5);
                     randomNumbers = numericCharacters.sort(() => Math.random() - 0.5);
                     lowerCasedCharacters.sort(() => Math.random() - 0.5);
                     upperCasedCharacters.sort(() => Math.random() - 0.5);

// checking user's input if true will utilise the above math.random arrays + brings all arrays together in one array if true
if (lowerCaseCharacters === true) {
  allArrays = allArrays.concat(lowerCasedCharacters);
}

if (upperCaseCharacters === true) {
  allArrays = allArrays.concat(upperCasedCharacters);
}

if (numberCharacters === true) {
  allArrays = allArrays.concat(randomNumbers);
}

if (oddCharacters === true) {
  allArrays = allArrays.concat(specialCharacters);
}

// randomizes the array
    randomArray = allArrays.sort(() => Math.random() - 0.5);

//sets array length based on passwordLength input

    randomPassword = randomArray.slice(0,passwordLength) 

I++
  }
  return randomPassword
};
Enter fullscreen mode Exit fullscreen mode

A function called getRandom(arr) is defined. This function will be used to randomly select an element from the arrays of characters that were defined earlier in the code. The function uses the JavaScript sort() method to randomly shuffle the elements in each array.
These if statement checks the value of the variables. If it is true, it means that the user has selected to include lowercase characters in their password. The code then uses the JavaScript concat() method to add the elements to the randomArray.
It then uses the JavaScript sort() method to randomly shuffle the elements in the randomArray variable. The function passed to sort() uses Math.random() and a subtraction operation to randomly order the elements in the array. This ensures that the elements in the randomArray are in a random order.
Finally, it slices with slice() method to select a specific number based on the user’s initial input.


Finally, the code will generate your unique password and store it in the randomPassword array, ready for you to use to lock away all of your important online accounts.

// Function to generate password with user input
function generatePassword() {
    let finalPassword = getRandom();
    finalPassword = finalPassword.join("")
    return finalPassword
}
Enter fullscreen mode Exit fullscreen mode

To end things it uses the join() method to convert the finalPassword variable, which is an array, into a string. The argument passed to the join() method, in this case, is an empty string ("").
This means that the elements of the array will be concatenated without any separator, ready to be copied by the user.


So don’t settle for a weak and easily hackable password, let our interactive password generator be your key to a safer online experience. Give it a try today!

Latest comments (0)