In JavaScript, does it make a difference if I call a function with parentheses?

前端 未结 5 594
不知归路
不知归路 2020-11-22 02:13

I noticed a difference when calling a function with empty parentheses, or without any parentheses at all. However, I am not passing any arguments to the function so I wonder

5条回答
  •  一整个雨季
    2020-11-22 03:14

    I'm 6 years late but I feel this could have been explained a lot simpler than the above answers.

    So here is the TLDR; or bird's eye view when calling functions using and not using ()'s

    Lets take this function for example:

    function foo(){
    return 123;
    }
    

    if you log "foo" - without ()

    console.log(foo); 
    
    ---outout------
    function foo(){
    return 123;
    }
    

    Using no () means to fetch the function itself. You would do this if you want it to be passed along as a callback.


    if you log "foo()" - with ()

    console.log(foo());
    -----output-----
     123
    

    Using () after a function means to execute the function and return it's value.

提交回复
热议问题