Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Javascript maximum call stack exceeded

'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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading