I'm new with Javascript so it's a little difficult to me to explain this properly.
I have this recursive function:
function askQuestion(question){
let answer = prompt(question);
if(answer === ""){
alert("The answer is empty...");
askQuestion(question);
}
return answer;
}
So, the problem: if the user response was empty and the function is called again, when the user indicates a non empty response the value of "answer" remains empty. I notice that the call stack of chrome is calling again the function even when the answer is empty. I can't understand why this is happening, but I suspect the problem is there. I tried to "reset" the value of answer to null, but then the value of answer stays as null.
๐ท screenshot of the chrome inspect
Also, I'm not totally sure that this kind of functions are called recursive function... ๐
You can use a while loop instead, checking while the answer is empty to call the prompt(question)
while(answer === ""){
answer = prompt(question);
}
return answer;
you should return the function result
const askQuestion = question => {
let answer = prompt(question);
if(answer === '') {
alert("The answer is empty...");
return askQuestion(question);
}
return answer;
}