Search code examples
recursionreturnclosures

Not understood return behavior of recursive function with closure


The foundations of my programming "skills" are shaking.. I don't know if this behavior is caused by the recursion, closure or something else, but this is by far the weirdest thing I've seen so far.

My original intention was to use recursion to count the parents of dom element. The closure is implemented to store my counter and recursion would increase it for every parent that is not equal to div#wrapper. And it works - once. For the first element (having only 1 parent - it returns 1) However the second time it returns undefined. for the sake of testing I came up with this rig:

let parents = countParents();
let pathLength = parents(3);

function countParents() {
    let counter = 0;
    return function nextParent(node) {
        let parent = node - 1;
        counter++;
        if (parent === 1)
            return 'WATAFAK';
        else
            nextParent(parent);
    }
}

console.log(pathLength);

I am actually questioning my eyes (it's late, been programming for a while now), but this function returns undefined. HOW is that possible?


Solution

  • function countParents() {
        let counter = 0;
        return function nextParent(node) {
            let parent = node - 1;
            counter++;
            if (parent === 1)
                return 'WATAFAK';
            else
                nextParent(parent); // call nextParent(parent) and throw away result
            return undefined;       // invisible line in every function
        }
    
        return undefined;           // invisible line in every function (never reached)
    }
    

    If you wanted the result of the recursion to be the result you must add return in front of it. How it is now it's only for side effects and it's pretty much dead code.

    Since the else branch doesn't return all functions have a invisible return undefined, just before its block ends.