I am working with this following code in order to make a simple password generator. The issue I am facing is that when the passwordLength function is run, and no answer is given, it goes through the given process, including alerting me: "Incorrect value. Please choose a number between 8 and 128." Following that prompt the function is re-run. However, when I re-enter my value(this time with a correct value). It goes through to the "return lengthInput", but doesn't return the value I just input. It returns the value that was generated in the first loop. In this case, that would be null. How do I get it to return the value I just typed in rather than sending the value that was previously run through the loop?
You should always create an SO snippet to present your actual problem. In your case you forgot to store the returned value of the recursion call in the variable lengthInput:
const passwordLength = function() {
var lengthInput = window.prompt("How long do you want your password to be? Please choose a number between 8 and 128.");
if (lengthInput < 8 || lengthInput > 128) {
window.alert("Incorrect value. Please choose a number between 8 and 128.");
lengthInput=passwordLength();
}
return lengthInput;
};
console.log(passwordLength())
The code in this snippet is still overcomplicated, as it will unnecessarily go into a recursion. But at least it will use the latest "legal" value for lengthInput.
A simpler solution to your problem might be:
const passwordLength = function() {
var lengthInput;
while ((lengthInput = window.prompt("How long do you want your password to be? Please choose a number between 8 and 128.")), lengthInput < 8 || lengthInput > 128)
window.alert("Incorrect value. Please choose a number between 8 and 128.");
return lengthInput;
};
console.log(passwordLength())
Or even:
const passwordLength = function() {
do var lengthInput = window.prompt("How long do you want your password to be? Please choose a number between 8 and 128.");
while (lengthInput < 8 || lengthInput > 128)
return lengthInput;
};
console.log(passwordLength())