Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

152
Views
Recursive function getting called repeatedly despite conditional logic

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... ๐Ÿ˜…

about 4 years ago ยท Juan Pablo Isaza
2 answers
Answer question

0

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;
about 4 years ago ยท Juan Pablo Isaza Report

0

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;
}
about 4 years ago ยท Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
ยฉ 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!