Open In App
Related Articles

How to Generate a Random Password using JavaScript ?

Improve Article
Improve
Save Article
Save
Like Article
Like

This article will show you how to generate a random password that may consist of alphabets, numbers, and special characters. This can be achieved in various ways.

In this article, we will discuss the most popular two methods which are discussed below to solve the problem. 

Approach 1: Make a string consisting of Alphabets (lowercase and uppercase), Numbers, and Special Characters. We will use Math.random() and Math.floor() methods to generate a number between 0 and l-1 (where l is the length of the string). To get the character of the string of a particular index we can use .charAt() method. This will keep concatenating the random character from the string until the password of the desired length is obtained.

Example: This example implements the above approach. 

Javascript




/* Function to generate combination of password */
function generatePass() {
    let pass = '';
    let str = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' +
        'abcdefghijklmnopqrstuvwxyz0123456789@#$';
 
    for (let i = 1; i <= 8; i++) {
        let char = Math.floor(Math.random()
            * str.length + 1);
 
        pass += str.charAt(char)
    }
 
    return pass;
}
 
console.log(generatePass());


Output

QqW9Ohc2

 Approach 2: In this approach, we will use Math.random() method to generate a number in between 0 and 1 then convert it to base36(which will consist of 0-9 and a-z in lowercase letters) using .toString() method. To remove the leading zero and decimal point slice() method will be used and Math.random().toString(36).slice(2) to generate the password. For uppercase letters use the same method with .uppercase() method in concatenation with the previous method.

Example: This example implements the above approach. 

Javascript




function randomPassword() {
    console.log(
        Math.random().toString(36).slice(2) +
        Math.random().toString(36)
        .toUpperCase().slice(2));
}
 
randomPassword();


Output

7wnrr29q18dF3IRQHMPTCW

Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!

Last Updated : 11 Aug, 2023
Like Article
Save Article
Previous
Next
Similar Reads
Complete Tutorials