It’s happened. You’ve been coding a bit and you receive an error in your console or in your chrome dev tools that says uncaught rangeerror: maximum call stack size exceeded…
with a traceback. What does it mean?
Reason: Recursive function does not have a base case
When we write a recursive function, we need to have a base case to stop the recursive call. Otherwise, it will continue calling the recursive function until you run out of call stack room. This is called an infinite loop.
Here is a code example that will result in that error:
function recursiveExample(n) { console.log(n) return recursiveExample(n - 1); } console.log(recursiveExample(10));
We need to give the block of code a place to stop. To do that, we need to add a conditional statement that will be the function’s “base case”. This will signal the recursion to stop.
function recursiveExample(n) { if(n === 0) { //this is our base case and will signal code to stop running. console.log("LIFTOFF!"); return "🚀"; } console.log(n) return recursiveExample(n - 1); } console.log(recursiveExample(10));
Remember to add a base case to your recursion function if you plan to use it. It will save you an error like this one from happening!
About us: Career Karma is a platform designed to help job seekers find, research, and connect with job training programs to advance their careers. Learn about the CK publication.