Home > Mobile >  Why javascript error stack for just one loop?
Why javascript error stack for just one loop?

Time:07-16

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));

CodePudding user response:

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));

  • Related