How to Generate Random Secure Passwords Using JavaScript

May 19, 2023

Using strong and secure passwords is crucial for protecting sensitive information. It is also challenging to come up with a new password when you need it.

That's why you can generate random and secure passwords using JavaScript on your website. We will dive into this topic and explain the whole process.

To secure your passwords, you can include uppercase and lowercase letters, numbers, and special symbols. You can customize the length of the password as well.

HTML Structure to Generate Password

Before going to the JavaScript logic let's write some HTML to create a web page. This page will contain some buttons, checkboxes, and inputs for customizing our passwords.

This is the HTML structure we will use in this post:

          <div class="container">
    <h2>Password Generator</h2>
    <div class="password-container">
        <input type="text" id="password"> <!-- Input to display password -->
        <button class="copy-result" id="copy">Copy</button> <!-- Button to copy the password to clipboard -->
    <div class="settings">
        <div class="input-group">
            <label>Password length (4-20)</label>
            <input type="range" id="pass-length" min='4' max='20' step="1" /> <!-- Input to set the password length -->
            <span id="length-result">12</span>
        <div class="input-group">
            <label>Include numbers</label>
            <input type="checkbox" id="numbers" checked /> <!-- Checkbox to include numbers in the password -->
        <div class="input-group">
            <label>Include symbols</label>
            <input type="checkbox" id="symbols" checked /> <!-- Checkbox to include special symbols in the password -->
    <button class="generate-btn" id="generate">Generate</button> <!-- Button to generate the password -->

I have an input field with the type "text" and an id of "password". It will display the generated password. There is a button with an id of "copy", it will allow us to copy the generated password to our clipboard.

Here I also have 3 additional <input> fields. The range type input field is used to select a password length within the range of 4 to 20 characters.

The next 2 input fields are "checkbox" types. By default, these fields are selected, indicating that numbers and special symbols are included in the generated password.

However, you have the flexibility to check or uncheck these fields according to your preference. Checking them ensures that numbers and special symbols are included while unchecking will exclude them from the password generation process.

Finally, there is a button with a class of "generate-btn" and an id of "generate". When we click this button, it will generate a random password based on the above settings.

Also Read: How to Convert Title or String to URL Slug Using JavaScript

Generate Random Secure Passwords With JavaScript

Even though we have all the HTML elements in place, these won't work without JavaScript. You have to include a JavaScript file to your HTML page to add functionality to those elements.

First, select all the necessary elements from your HTML page in the JavaScript file using the document.getElementById method.

          const copy = document.getElementById('copy') // Button to copy password to clipboard
const generate = document.getElementById('generate') // Button to generate password
const numbers = document.getElementById('numbers') // Checkbox to include numbers in password
const symbols = document.getElementById('symbols') // Checkbox to include symbols in password
const passLength = document.getElementById('pass-length') // Input to get password length
const passwordInput = document.getElementById('password') // Input field to display password
const passLengthResult = document.getElementById('length-result') // Display the length of the password

Now we will write some JavaScript code to get a password. For that, we will create a function called generatePassword() which will contain all the logic.

When we call this function, it will give us a random password.

          // Generate password
const generatePassword = () => {
    let password = ''

    const length = passLength.value
    const isIncludeNumbers = numbers.checked
    const isIncludeSymbols = symbols.checked

    let characters = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz'

    if (isIncludeNumbers) {
        characters += '0123456789'

    if (isIncludeSymbols) {
        characters += '!@#$%^&*(){}[]=<>/'

    for (let i = 1; i <= length; i++) {
        var index = Math.floor(Math.random() * characters.length + 1)

        password += characters.charAt(index)

    passwordInput.value = password

// Listen for password range change
passLength.addEventListener('change', (event) => {
    passLengthResult.innerText =


Next, it retrieves the value of the passLength variable, which represents the desired password length.

Note: To get the password length from the range input, you have to listen to the change event by calling the addEventListener() on the passLength variable.

It also checks the values of the numbers and symbols variables, which correspond to the checkboxes for including numbers and symbols in the password, respectively.

The characters variable contains all the lowercase and uppercase letters. If the numbers checkbox is checked (isIncludeNumbers is true), we will include digits from 0-9 in these letters.

Similarly, if the symbols checkbox is checked (isIncludeSymbols is true), we will also add some special characters to our characters variable.

Now we will execute a for loop length number of times, where length represents the desired password length. In each iteration, this loop will generate a random number within a specific range (from 0 to the length of the character variable).

Use this number as an index to extract a character from the characters string using the charAt method and concatenate to the password variable.

After the loop completes, we will get our generated password in the password variable. You can display it on your web page by assigning it to the value property of the passwordInput element.

Get Random Passwords on Page Load and Button Click

Creating the generatePassword() function won't do anything. We also have to execute this function. We will call it in two ways.

First, when you click the "generate" button on the page and when the page loads. Listen to the click event on the generate button and call generatePassword function.

          // Generate a random password on button click
generate.addEventListener('click', generatePassword)

// Generate a random password on page load
document.addEventListener('DOMContentLoaded', generatePassword)

Trigger the generatePassword function on the DOMContentLoaded event. This event will run the generatePassword function when the page finishes loading.

This ensures that a random password is generated as soon as the page is ready. You don't need to click the "Generate" button manually.

Also Read: How to Sanitize HTML Using JavaScript: Prevent XSS Attacks

Copy The Password to The Clipboard

When you have generated your password, you can use the "Copy" button to copy it to the clipboard. Add the click event listener to the copy button.

          // Copy password to the clipboard
copy.addEventListener('click', async () => {

    await navigator.clipboard.writeText(passwordInput.value)

When you click the "copy" button, it will execute the event callback function. Inside this function, select the text in the input field by calling the select() method.

You can copy the text to the clipboard in JavaScript using the navigator.clipboard API.


We have explored the process of creating a password generator tool that allows users to create strong passwords using JavaScript. You can also add some settings.

You can increase or decrease the password length and include numbers and special symbols to make them strong and secure.

You can generate random passwords by clicking a button and on the page load. Finally, for a seamless experience add a "Copy" button to copy the generated password to the clipboard.

Related Posts