CodingNic

Password Generator

Fill, Shuffle, and Render the Password

Password Generator 18 min read

Fill, Shuffle, and Render the Password

Fill, Shuffle, and Render the Password

You have the building blocks. Now finish the core algorithm in separate steps.

1. Read the requested length

After resolving enabled, read the slider and prevent it from being smaller than the number of guaranteed category characters:

javascript
const length = Math.max(Number(lengthRange.value), enabled.length);
lengthRange.value = length;
lengthValue.textContent = length;

2. Fill the remaining positions

After the guaranteed-character loop, add:

javascript
while (characters.length < length) {
  characters.push(pool[secureRandom(pool.length)]);
}

Now the array has exactly the requested number of characters.

3. Shuffle the array

Because the guaranteed characters were inserted first, their positions would otherwise be predictable. Add this helper above generatePassword():

javascript
function shuffle(values) {
  for (let i = values.length - 1; i > 0; i -= 1) {
    const j = secureRandom(i + 1);
    [values[i], values[j]] = [values[j], values[i]];
  }
  return values;
}

Then turn the shuffled array into the displayed string:

javascript
const password = shuffle(characters).join("");
output.textContent = password;

4. Connect Generate

Outside the function, add:

javascript
generateButton.addEventListener("click", generatePassword);
generatePassword();

The first line responds to clicks; the second gives the page an initial password.

Test

Generate passwords at several lengths. Change character selections and confirm the output follows them. Select all four categories at a short length and confirm the generator does not crash.

Checkpoint

SecureGen now has a complete core generation path: length → selected sets → guaranteed characters → remaining characters → shuffle → output.