Phillip Senn
Phillip Senn

Reputation: 47605

When do I use parentheses and when do I not?

How come I can say:

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

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

Upvotes: 17

Views: 4625

Answers (5)

Dave Newton
Dave Newton

Reputation: 160191

Nutshell

  • myFunction references the function
  • myFunction() calls the function

More Words

setTimeout expects a function reference* as an argument.

There are circumstances where setTimeout(myFunction(), 1000) might make sense, like if myFunction() returns a function, e.g.

function myFunction() {
    return function() {
        alert("ohai")
    }
}

// Or

const myFunction = () => () => alert("ohai")

So:

setTimeout(myFunction(), 1000);
  • setTimeout gets the return value of myFunction
  • myFunction returns a function (that calls alert)

meaning there will be an alert every second.

See also Why function statement requires a name?

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

Upvotes: 22

Safwat Fathi
Safwat Fathi

Reputation: 1005

I think this example would make it clearer if i may,

function callback() {
  console.log('this function runs on page loads.');
}

setTimeout(callback(), 2000); 

Here callback() function will run immediately after page loads and won't wait 2 seconds.

function callback() {
  console.log('this function runs after page loads.');
}

setTimeout(callback, 2000);

Here callback() function will run after 2 seconds.

Upvotes: 1

Chris
Chris

Reputation: 1049

When you use the parenthesis, it's saying 'call this function now'. So if you say setTimeout(myFunction(),1000);, it will use the return value of the function as the callback for the timeout. If the return value for the function is not itself a function, you'll get an error because it will try to execute something that isn't executable after the timeout (a string, a number, undefined, etc).

Upvotes: 7

hugomg
hugomg

Reputation: 69934

myFunction is a function

myFunction() calls the function and yields whatever value the function returns.

The purpose of setTimeout is running code after some time elapses. You need to pass just the function to it (so setTimeout can itself call the function when appropriate) because if you called the function (with the parenthesis) before passing it to setTimeout it would execute now instead of after 1 second.

Upvotes: 11

Luc125
Luc125

Reputation: 5857

In line 2, the function myFunction is not called, but passed as an argument to the setTimeout function, whereas in line 4 myFunction is called; to call a function, you always have to use parentheses, even if there are no arguments.

Upvotes: 2

Related Questions