Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

154
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda