javascriptrecursion

Getting return undefined on recursive function javascript


I heard recursive function is powerful so instead going through loop i tried to create a function which increments a number until it reach certain points. when it reaches i tried to return the value, but it give undefined.

CODE

var i=1;
function rec(){
    i++;
    console.log(i);
    if(i > 100){
        return i;
    }else{
        rec();
    }
}

console.log(rec());

Here the i is incrementing until 100. but it returns undefined after the limit. Why is this happening? Also please let me know, it this kind of recursion is good then for loop?


Solution

  • The comment by vaultah is correct:

    let i = 1;
    function rec() {
        i++;
        console.log(i);
        if (i > 100) {
            return i;
        } else {
            return rec();
        }
    }
    
    console.log(rec());


    Let's take an example that only counts to > 5 and add some output so you can see what happens more easily (but again, stepping through the code with a debugger is the right way to see how this works):

    let nesting = 0;
    let i = 1;
    function rec() {
        let rv;
        ++i;
        ++nesting;
        if (i > 5) {
            log(`${i} > 5, returning ${i}`);
            rv = i;
        } else {
            log(`${i} is not > 5, calling rec`);
            rv = rec();
            log(`Got ${rv} back from rec, returning it`);
        }
        --nesting;
        return rv;
    }
    
    log("Final result: " + rec());
    
    function log(msg) {
        console.log(" ".repeat(nesting) + msg);
    }