Home Java Tutorial Random Password Generator using Javascript

Random Password Generator using Javascript

by Anup Maurya
12 minutes read

Generating a random password is an important task in many web applications that require users to create secure and unique passwords. In this article, we will look at how to write a JavaScript program to generate a random password.

There are many ways to generate a random password, but one common method is to use a combination of letters, numbers, and special characters. Here’s an example of a JavaScript program that generates a random password using this method:

Random Password Generator using Javascript

function generateRandomPassword(length) {
  const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*()_+{}|:<>?-=[];,./`~';
  let password = '';
  for (let i = 0; i < length; i++) {
    const randomIndex = Math.floor(Math.random() * characters.length);
    password += characters[randomIndex];
  return password;

const length = 12;
const randomPassword = generateRandomPassword(length);

Let’s break down this code to understand how it works.

First, we define a function called generateRandomPassword that takes a single parameter length, which specifies the length of the password we want to generate.

Inside the function, we define a string called characters that contains all the characters we want to include in our password. This string includes upper- and lower-case letters, numbers, and various special characters.

Create a comprehensive study plan with key topics and resources to excel in your Microsoft Certification Test.

We then define an empty string called password, which we will use to store the generated password.

Next, we use a for loop to generate a random character for each position in the password. Inside the loop, we generate a random index between 0 and the length of the characters string using the Math.random() function. We use Math.floor() to round the random number down to the nearest integer. We then use this random index to select a random character from the characters string, which we append to the password string using the += operator.

Finally, we return the password string.

To test our function, we define a variable called length that specifies the length of the password we want to generate. We then call generateRandomPassword with this length as the parameter, and assign the result to a variable called randomPassword. We log this variable to the console to see the generated password.

If you run this code, you should see a different random password printed to the console each time.

In conclusion, generating a random password in JavaScript is a straightforward task that can be accomplished using basic string manipulation and the Math.random() function. By using this technique, we can ensure that our web applications generate secure and unique passwords for our users.

related posts

Leave a Comment