Search code examples
javascriptfunctionvariablesscopereturn

Where does a returned function go if not stored somewhere?


Where does a returned function go if not stored somewhere? Shouldn't it get appended to the global object/current outer-context? Here's an example:

var setup = function(){
    console.log("xyz");
    return function goBack(){
        console.log("It's actually abc");
    }
}

Now, on calling setup() in the global scope, "xyz" is being shown in the console, but the returning function, i.e goBack is not being appended in the global scope.

setup() //Outputs "xyz"

Now, on trying to call goBack, it's undefined in global scope:

goBack() //error: goBack not defined

Now I could access goBack using setUp()() or by storing the returned function from setup() into a global variable. But, shouldn't I be able to access goBack from the global scope once I execute setup() ? Because if I had stored setup() into a global variable, I would have access to goBack via that variable. But what happens if I don't use a variable to store the returned function from setup()? Where does goBack return to exactly? Thank you.


Solution

  • You're returning a function object, which is the same as any other kind of object, or any other sort of value. If you don't assign it to anything, it simply goes out of scope and will be garbage collected. Nothing happens with it.