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

121
Visualizações
Why javascript error stack for just one loop?

Why error stack even for n = 1?

function f(n) {
  const f1 = f(n - 1);
  const f2 = f(n - 2);
  return n == 0 ? 0 : (n == 1 ? 1 : f1 + f2);

}

console.log(f(1));

about 4 years ago · Santiago Gelvez
1 Respostas
Responde à pergunta

0

Because your base case conditional is after you perform a recursive call, you'll always hit the first line, the function will call itself, then the first line will be run, the function will call itself, forever. You need your base case conditional statement before any unconditional recursion (note that I've literally replaced f1 and f2 with their definitions below):

function f(n) {
  return n == 0 ? 0 : (n == 1 ? 1 : f(n - 1) + f(n - 2));
}

console.log(f(1));

This is probably a bit neater (handle base cases individually, then return the sum of the two recursive components):

function f(n) {
  if (n == 0) return 0;
  if (n == 1) return 1;
  const f1 = f(n - 1);
  const f2 = f(n - 2);
  return f1 + f2;
}

console.log(f(1));

about 4 years ago · Santiago Gelvez 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