Search code examples
javascriptclassreturn

How does returning a function inside a function work


I feel like my example explains it well. I am unsure of how a function returning inside a function works. I feel like solving the below demo would help me understand. Any other links or documents would be nice to read though as well.

function LogFunction() {
  return function() {
    return "just console log this";
  };
}

console.log(LogFunction());
// "just console log this"   <<< I want this
// "[Function]"              <<< I am getting this

Solution

  • In JavaScript functions are known as "First-class function" this means you can return / pass functions as any other type like (object / numbers). You can find more about this here.

    You can break this one into variables to make it more clear such as:

    function LogFunction() {
      return function() {
        return "just console log this";
      };
    }
    
    var a = LogFunction()
    console.log( a() );
    

    However as others pointed correctly you can call this directly

    console.log( LogFunction()() );
    

    On the variables examples, when a LogFunction() is called with () you are invoking the function and the result of this invocation is assigned to the variable a, as the result of invoking the function is another function you need to call the result of the previous function in order to access the result of this function a().

    You can have as many levels of nested function as you wish, and with the new ES2016 you can take advantage of arrow functions to make this code much clear.

    const LogFunction = () => () => "just console log this";
    console.log( LogFunction()() );