Home > Back-end >  Javascript maximum call stack exceeded
Javascript maximum call stack exceeded

Time:10-09

'use stict';

function sumToRecursive(n) {
  if (n === 1) {
    return 1;
  }

  return n   sumToRecursive(n - 1);
}

function measureFunctionSpeed(f) {
  let start = Date.now();

  for (let i = 0; i <= 10; i  ) {
    f(i);
  }

  let end = Date.now();

  return end - start;
}

console.log(measureFunctionSpeed(sumToRecursive));

I'm getting a 'maximum call stack exceeded' error when I try to run the code above but I learned that the max call stack limit is around 10,000. My code goes 10 recursive levels deep at most but throws the same error. Does anyone know why?

Screenshot of execution result

CodePudding user response:

The first iteration of the loop feeds the function 0 as i, which is not covered in the base case.

You can either start the for loop from i= 1 or change the base case check to if (n <= 1) {} to cover the 0 case.

  • Related