Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

123
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda