Use functions and loops to create a reusable password generator. Given a desired length, it should return a random mix of letters and numbers.
YOUR TASK
Create a program that:
Defines a function generatePassword(length)
Uses a character set of letters + numbers
Loops length times, picking a random character each time
Returns the assembled password string
Calls the function and logs the result
Need a hint?
Step-by-step:
1. const chars = "abcdefghijklmnopqrstuvwxyz0123456789";
2. function generatePassword(length) {'{'}
3. let password = "";
4. for (let i = 0; i < length; i++) {'{'}
5. const index = Math.floor(Math.random() * chars.length);
6. password += chars[index];
7. {'}'}
8. return password;
9. {'}'}
10. console.log(generatePassword(8));
Example output (length = 8):
k4m9z1qr
(random — yours will differ each run)
Code Editor
Ready
Output
Console
Console initialized...
Ready for Project 5: Random Password Generator
> Click "Run Code" to generate a password
> Click "Check My Code" to verify your solution