Generate passwords with JavaScript

The function generatePassword() is a simple yet customizable function that generates a random password string, the default password length is 6, you can override it by calling the function like thisĀ  generatePassword(n) where n is the password length. The possible characters are defined within the function with the variable chars

The function: generatePassword([len=6])

function generatePassword(len){
	len	= parseInt(len);
	if(!len)
		len = 6;
	var password = "";
	var chars    = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
	var charsN   = chars.length;
	var nextChar;

	for(i=0; i<len; i++){
		nextChar = chars.charAt(Math.floor(Math.random()*charsN));
		password += nextChar;
	}
	return password;
}

Usage

The first example show the function without the optional len patamater(string length), and second example makes use of it:

// Example 1: No len
window.alert("A random string of 6 characters: " + generatePassword());

// Example 2: Using len
pwdLen = 10;
window.alert("A random string of " + pwdLen + "characters: " + generatePassword(pwdLen));

Try it

Generate a random password of 16 characters.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top