Javascript function call with/without parentheses
Asked Answered
M

6

4

code_0:

(calling foo without parentheses)

function foo(){
    console.log('hello world');
}

setTimeout(foo, 2000);

This is how code_0 was executed:

start -> wait for 2 seconds -> 'hello world' displayed -> end

code_1:

(calling foo with parentheses)

function foo(){
    console.log('hello world');
}

setTimeout(foo(), 2000);

And this is how code_1 was executed:

start -> 'hello world' displayed immediately -> wait for 2 seconds -> end

Why would the program perform so differently when I called the function with parentheses? What is the underlying mechanism?

Sorry if this question is too trivial. But I could't find an explanation on any javascript tutorial for beginners.

Morgue answered 2/1, 2016 at 6:37 Comment(0)
S
7

setTimeout(foo, 2000) passes the function foo and the number 2000 as arguments to setTimeout. setTimeout(foo(), 2000) calls foo and passes its return value and the number 2000 to setTimeout.

In the first example, you’re not calling the function at all, just passing it as an argument like any other value.

As a simpler example, just log it:

function foo() {
    return 5;
}

console.log(foo);   // console.log is passed a function and prints [Function]

console.log(foo()); // foo() is called and returns 5; console.log is passed 5
                    // and prints 5
Spann answered 2/1, 2016 at 6:41 Comment(5)
So what if the function foo has an argument. Like: function foo(arg){ console.log('hello' + arg); } How do I use setTimeout on foo but also pass the parameter 'world' to foo?Morgue
@Delsin: You can pass a function that calls that function in turn. For example: setTimeout(function () { foo('some argument'); }, 2000);. There is also a built-in function on functions, bind, that sets this and some leading arguments: setTimeout(foo.bind(null, 'some argument'), 2000);Spann
@RyanO'Hara - Making that a little complex, aren't ya? After the delay argument any extra args you give get sent to the function. Example: setTimeout(foo, 2000, myArg1, myArg2, myArg3);Why not just do that?Housekeeping
@RyanO'Hara - Nevermind, just answered my own question by remembering that a bunch of IE versions don't support that. But to be fair, bind isn't much better supported by IE either.Housekeeping
@JimboJonny: I didn’t want to make the answer specific to one usage.Spann
C
3

In the first code snippet, the function foo is being passed to the timeout. That means that foo gets called after 2 seconds when the timeout expires.

In the second code snippet, the function foo is being called to decide what to pass to the timeout. So foo gets called before the timeout is set. Since foo() doesn't return anything, nothing happens when the timeout expires.

Cavalcade answered 2/1, 2016 at 6:43 Comment(0)
C
2

In your question, foo is

function foo(){
    console.log('hello world');
}

whereas foo() is

console.log(hello world)

The setTimeout() method calls a function or evaluates an expression after a specified number of milliseconds, and this function is supposed to be the first parameter to it, in your first case you are passing a function that is why the behaviour is expected and in the second case you are passing console.log(...) which is not a function, so it is executing foo() first and prints in console hello world then waits for 2 sec and do nothing and thus showing wierd behaviour.

See

typeof foo; // is function

typeof foo(); // prints hello world in console first and then says undefined.

Corell answered 2/1, 2016 at 6:44 Comment(0)
S
2

The basic difference between foo and foo() is the following:

function foo() {
   alert("bar");
   return "baz";
}

console.log(foo); // gives "function"
console.log(foo());  // gives "baz"

foo is a reference to the function body itself while foo() executes the function. Thus

setTimeout(foo(), 2000);

passes the return value ("baz") to the function setTimeout(which will result in an error). setTimeout expects an "executable" function as first argument, so you need to pass in a reference to an existing function.

Sarina answered 2/1, 2016 at 6:47 Comment(0)
H
1

The point of confusion here is that you're not realizing that using foo without parentheses is not calling the function...it's only referencing it.

foo is the reference to the function itself. To call a function (i.e. actually execute its code) you reference it with parentheses at the end (e.g. foo()). In a practical sense that means:

// references the function itself
// ...you could call one() now and it would run the function foo
var one = foo;

// runs/calls the function, and var two will then be whatever foo returns
var two = foo();

So in the first example you are NOT calling the function. You are passing the function foo to setTimeout. setTimeout will then call it after a delay.

In the second example you called foo immediately and passed whatever foo returns to setTimeout (which setTimeout couldn't do anything with, because that return value likely wasn't another function). So your function was executed immediately and then nothing would have happened (except likely some errors) after setTimeout was done with its delay.

Housekeeping answered 2/1, 2016 at 7:4 Comment(0)
P
0

Here's an easy solution. You can use parentheses and pass data to the function if needed.

<script> function foo(){alert("hello world")} setTimeout(function() {foo()}, 2000) </script>

Preshrunk answered 25/1, 2019 at 13:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.