Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recursive javascript function causing "Maximum call stack size exceeded"

During the course of designing a small API at work and trying to make my functions as flexible as possible I decided to start adding checks for whether arguments are passed, and then based on that, do different things. So when the function is called with a number, the function uses the number as an index in an array. If no number is passed, I wanted the function to call itself as many times as the length of the array. However I get the call stack error. I have boiled the problem down to the recursion aspect of the function, which I'm listing below. The thing that is strangest to me is this...

THIS CAUSES ERROR

function testing(a){
    if(!a){
        for(var i = 0; i < 3; i += 1){
            testing(i);
        }
    }else{
        alert(a);
    }
}

testing();

THIS DOES NOT CAUSE ERROR

function testing(a){
    if(!a){
        for(var i = 0; i < 3; i += 1){
            testing(5);//Just adding hard coded number instead
        }
    }else{
        alert(a);
    }
}

testing();

I'm trying to understand why passing the var in the call throws an error. It seems that if the js engine can hold the initial function call in memory in order to make the for loop work properly why couldn't it hold a reference to i while calling itself? I feel like I am missing something fundamental here. I've tried lots of rewrites involving things like:

testing(function(i){return i;}(i));

All to no avail. This is driving me crazy and I would like to understand what is going on here.

like image 779
carter Avatar asked Dec 26 '22 15:12

carter


1 Answers

if a===0 it is false, that means you have an infinite loop

for more details, read this and this (thanks @yochannah )

like image 142
bbuecherl Avatar answered Dec 28 '22 06:12

bbuecherl