JavaScript recursion


  • 0
    B

    Encountered this behavior in a project I'm working on. Basically, using recursion to consume a list. I've extracted the core in the below snippet:

    (function main() {
        var count = 10;
        function consume() {
            if (count > 0) {
                count--;
                if (count % 2 == 0) {
                    consume();
                }
                console.log(count);
                consume();
            }
        }
        consume();
    }());
    

    Expected output is, of course:

    9
    7
    5
    3
    1
    

    Actual output is, strangely:

    9
    7
    5
    3
    1
    0
    0
    0
    0
    0
    

    What sorcery is this!?


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.