Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When do I use parenthesis and when do I not?

Tags:

javascript

How come I can say:

var myFunction = function() {
   setTimeout(myFunction, 1000);
}
myFunction();

Why does the function call in the setTimeout not require a parenthesis, but the last line does?

like image 273
Phillip Senn Avatar asked Nov 01 '11 15:11

Phillip Senn


1 Answers

The setTimeout function expects a function reference* as an argument: references are variables, and don't have parentheses.

Function calls require parentheses (even if the function takes no parameters).

Nutshell: myFunction is a reference to the function. myFunction() executes the function, and in an expression, will "equal" the function's return value (or undefined if nothing is returned).

Digging Deeper: There are circumstances where setTimeout(myFunction(), 1000) might make sense, like if myFunction() itself returns a function. For example:

var myFunction = function() {
    return function() {
        alert("ohai");
    };
};
  • The anonymous function (containing a single return statement) is executed immediately.
  • The return value of that function is itself a function containing an alert.

So:

  • myFunction alone is a reference to a function (that happens to return a function).
  • myFunction() will execute. It evaluates to a function reference, suitable for setTimeout().

Finally:

setTimeout(myFunction(), 1000);

This calls myFunction()'s return value in one second. One second later, up pops the alert.

See also Why function statement requires a name?

* Or a string to be evaluated, but a reference is preferred.

like image 94
Dave Newton Avatar answered Sep 18 '22 06:09

Dave Newton