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?

1
  • Because functions are objects too. displayName is the function, and displayName() calls the function displayName and returns its value. Commented Aug 15, 2013 at 23:00

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

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.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.