Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

133
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!