Code Premix

Random Password Generator using JavaScript

📅October 1, 2021

Today we’ll show you how to generate a random password using JavaScript. Here, we’ll show you the most popular two methods to generate a random strong password using JavaScript.

  1. Generate a password from string
  2. Use Math.random() method

1. Generate a password from string

In this approach, we will create a custom function to get a random password where we have to pass the length of the password as a parameter. We’ll consider the string, number and symbol to generate a random password.

function generatePassword(len) {
  var length = len ? len : 10;
  var string = "abcdefghijklmnopqrstuvwxyz"; // to upper
  var numeric = "0123456789";
  var punctuation = "!@#$_";
  var password = "";
  var character = "";
  while (password.length 

2. Use Math.random() method

In the next approach, we’ll use the Math.random() method to cast a random number (in the range 0..1) to a base36 string (lowercase a-z plus 0-9) and remove the leading zero and decimal point using slice() method. Here, we have used the toUpperCase() method to get the uppercase char in the password.

function generatePassword() {
  return (
    Math.random().toString(36).slice(2) +
    Math.random().toString(36).toUpperCase().slice(2)
  );
}

generatePassword(); // Output: ggpq0gv9iviVI1YEF4BGZ
generatePassword(); // Output: bmsv4p3v4m1CFSR0V4CXH

That’s it for today.
Thank you for reading. Happy Coding..!!