0

Here is a code example from Mozilla about javascript closures:

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

var myFunc = makeFunc();
myFunc();

Why do you return inner function displayName() as a variable displayName, that is, without parentheses?

putvande
  • 15,068
  • 3
  • 34
  • 50
Leonardo DaVintik
  • 555
  • 1
  • 9
  • 18
  • Because functions are objects too. `displayName` is the function, and `displayName()` calls the function `displayName` and returns its value. – elclanrs Aug 15 '13 at 23:00

4 Answers4

2

If return displayName; had the parenthesis then it would call the function displayName inside `makeFunc' as apposed to returning the function itself.

aperl
  • 144
  • 3
2

return displayName() would

  1. invoke the alert at the line were var myFunc is set and
  2. return undefined.

return displayName (without the parentheses) returns the function itself whereas the former (with parentheses) invokes the function and returns whatever the function itself returns. As function displayName doesn't have an explicit return statement the implied return type is undefined.

Community
  • 1
  • 1
jandersen
  • 3,551
  • 22
  • 23
0

In that code sample, makeFunc is being called (it has parentheses) and its return value is assigned to myFunc.

Inside that function, return displayName is referring to the function and returning it.

The end result is that myFunc is a function with a predefined scope (where name="Mozilla"), and can later be called.

Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
0

In JavaScript, all functions are objects (of type Function). When you create a function, you're creating a new Function object and assigning it to a variable. In your case, you saved the function to the variable, displayName. If you want to return it, you put return [variableName], just like with any other object.

When you put () after the name of a variable storing a Function object, you are invoking the function. It's much like doing displayName.call(this). It's not exactly the same, as there are some important differences, but it's the same concept.

So if you put return displayName(), rather than returning a reference to the function itself, it would invoke the function and return whatever the function returned.

eyuelt
  • 1,386
  • 1
  • 15
  • 22