Search code examples
javascriptrecursionstack-overflow

Max Stack exceeded error, how would I fix this?


I am making a function that returns true if number in outerfucntion is within innerfunction list

<script>
function hasMatch(item) {
    hasMatch(2)  
    function inList() {
        var List = [1,2,3,4];
        for (i = 0; i<List.length; i++){
            if (list[i] == item) { 
                return true; 
            } else {
                return false;
            }
        }
    }
    inList();
}
hasMatch();
</script>

I get a "Max Stack exceeded error", how would I fix this?


Solution

  • hasMatch(2) is recursive call without any terminating condition.

    hasMatch() is getting called infinitely and that's why you see stack exceeded error.

    function hasMatch(item) { 
        function inList() {
            var List = [1,2,3,4];
            for (i = 0; i<List.length; i++){
                if (List[i] == item) { 
                    return true; 
                } else {
                    return false;
                }
            }
        }
        return inList();
    }
    
    hasMatch(2);