Search code examples
javascriptfunctioninvocation

Calling and assigning functions in JS without parenthesis


function makeFunc() {
  var name = "Mozilla";

  function displayName() {
    alert(name);
  }
  return displayName;
}

var myFunc = makeFunc();
myFunc();

The above code works even though displayName is without parentheses i.e. passing a reference to displayName which then would be invoked by makeFunc().

Now if you do return displayName(); var myFunc = makeFunc; It also works as expected. But if you do return displayName; var myFunc = makeFunc; it stops working.

It should've worked as those both functions would've been invoked by myFunc()?


Solution

  • A function reference is just a value in JavaScript. A function call is an expression involving two things: a reference to a function, and a parenthesized argument list.

    Without an argument list, a reference to a function is just a value.

    Thus, in your code:

    function makeFunc() {
      var name = "Mozilla";
    
      function displayName() {
        alert(name);
      }
      return displayName;
    }
    

    the identifier "displayName" in the function refers to that inner function. The return statement references that identifier without a parenthesized argument list. Thus, the return value from makeFunc() is a reference to that inner function. Assigning that to another variable gives that variable the same value, so then it can be used in a function call expression later.

    Note that you can call makeFunc() and call the returned function immediately:

    makeFunc()();
    

    That's a sequence of two function call expressions. The first is makeFunc(). That returns a function reference, so that function is called because of the second ().