javascriptparameter-passingparenthesesfunction-calls

Javascript function call with/without parentheses


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.


Solution

  • 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