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

125
Visualizações
Getting 'undefined' when trying to return a value from a recursive function

So I have this recursive function which takes in two parameters, factor and width. The factor will decrement in every recursive instance by 0.05. And in every instance it will be multiplied with width to get a value.

If this value is greater than 900 then the recursive function will continue. If it is less than 900 then it will stop and return the factor value.

Right now I'm getting undefined but if I log all the factors then I can see that there are numbers before undefined but it stops with undefined.

How can I get the factor value which is just before undefined?

Here's the snippet:

function findFactor(factor, width) {

  let nextFactor = factor - 0.05;
  let value = width * nextFactor;

  console.log(nextFactor);

  if (value < 900) {
    return nextFactor;
  } else {
    findFactor(nextFactor, width);
  }

}

console.log(findFactor(1, 2400));

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You are properly returning the result in case if (value < 900) {. However, you forgot to return the result of the subsequent recursive call. Adding return should solve your problem:

else {
  return findFactor(nextFactor, width);
}
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