Computer >> Computer tutorials >  >> Programming >> Javascript

How to create a password generator - JavaScript?


For this, use Math.random() to create random passwords.

Example

Following is the code −

function makePassword(maxLengthPass) {
   var collectionOfLetters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
   var generatedPassword = "";
   var size = collectionOfLetters.length;
   for (var i = 0; i < maxLengthPass; ++i) {
      generatedPassword = generatedPassword + collectionOfLetters.charAt(Math.floor(Math.random() * size));
   }
   return generatedPassword;
}
console.log(makePassword(5));

To run the above program, you need to use the following command −

node fileName.js.

Here, my file name is demo287.js.

Output

This will produce the following output on console −

PS C:\Users\Amit\javascript-code> node demo287.js
eeVK0