freeCodeCamp icon indicating copy to clipboard operation
freeCodeCamp copied to clipboard

Password Generator App - assigning to global `password` in function

Open gikf opened this issue 10 months ago • 3 comments

Describe the issue

Eighth test - You should call the `generatePassword` function with a numeric argument and store the returned password in the `password` variable. can pass with incorrect code.

Test will pass when password is used as a global variable, that's updated by the generatePassword function with each generated character. That's not right and makes pin-pointing what's wrong harder for campers.

Affected Page

https://www.freecodecamp.org/learn/full-stack-developer/lab-password-generator/lab-password-generator

Example code

let password = '';

const characters = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','0','1','2','3','4','5','6','7','8','9','!','@','#','$','%','^','&','*','(',')'];
const arrayLength = characters.length - 1;
const generatePassword = passwordLength => {
  for (let i = 0; i < passwordLength; i++) {
    let math = Math.round(Math.random() * (arrayLength - 0) + 0);
    password += characters[math]; 
  }
  return password
}

generatePassword(7);
console.log(`Generated password:${password}`);

Expected behavior

Test should check more reliably whether password variable is used as intended.

gikf avatar Feb 18 '25 09:02 gikf

Hang on. Test 3 is failing: Your generatePassword function should return a new string that is the correct length. . What other kind of tests should we add?

a2937 avatar Feb 18 '25 15:02 a2937

I don't think new test is necessarily needed, it's really more about making eighth test fail for such code.

Though I guess there could be new test generating two passwords and checking if the second one starts with first one.

gikf avatar Feb 18 '25 17:02 gikf

You should define a variable called password and assign it the result of calling the generatePassword function with a numeric argument that represents the desired password length.

How about a test to check whether the function call, with the required argument, is assigned to the password variable?

Supravisor avatar Feb 18 '25 17:02 Supravisor