When exactly is parenthesis needed when executing a function












0















I am new to JavaScript and would like to understand something about functions. Why is it that when calling a function to run, one usually has to end of with parenthesis (), and if not it will just display the contents of the function. But when binding an event listener to a element, one may not use parenthesis when calling the function and if they are used it will run as soon as the page loads. (same is true when using the setTimeout or SetInterval function).










share|improve this question




















  • 3





    When you're initializing an event listener, or initializing a timeout or interval you're not calling the function. You're passing the function to the framework to be called at a later designated time.

    – Patrick Roberts
    Nov 24 '18 at 19:11











  • So when is the function ever called

    – Joe Starbright
    Nov 24 '18 at 19:14











  • As I already said, it's called by the framework, not by you.

    – Patrick Roberts
    Nov 24 '18 at 19:16











  • Basically, thats how javascript works. It knows to call it by itself

    – Joe Starbright
    Nov 24 '18 at 19:20






  • 1





    @ScottMarcus The DOM (or whatever place where you register the callback) can be said to be a framework

    – Bergi
    Nov 24 '18 at 19:34


















0















I am new to JavaScript and would like to understand something about functions. Why is it that when calling a function to run, one usually has to end of with parenthesis (), and if not it will just display the contents of the function. But when binding an event listener to a element, one may not use parenthesis when calling the function and if they are used it will run as soon as the page loads. (same is true when using the setTimeout or SetInterval function).










share|improve this question




















  • 3





    When you're initializing an event listener, or initializing a timeout or interval you're not calling the function. You're passing the function to the framework to be called at a later designated time.

    – Patrick Roberts
    Nov 24 '18 at 19:11











  • So when is the function ever called

    – Joe Starbright
    Nov 24 '18 at 19:14











  • As I already said, it's called by the framework, not by you.

    – Patrick Roberts
    Nov 24 '18 at 19:16











  • Basically, thats how javascript works. It knows to call it by itself

    – Joe Starbright
    Nov 24 '18 at 19:20






  • 1





    @ScottMarcus The DOM (or whatever place where you register the callback) can be said to be a framework

    – Bergi
    Nov 24 '18 at 19:34
















0












0








0








I am new to JavaScript and would like to understand something about functions. Why is it that when calling a function to run, one usually has to end of with parenthesis (), and if not it will just display the contents of the function. But when binding an event listener to a element, one may not use parenthesis when calling the function and if they are used it will run as soon as the page loads. (same is true when using the setTimeout or SetInterval function).










share|improve this question
















I am new to JavaScript and would like to understand something about functions. Why is it that when calling a function to run, one usually has to end of with parenthesis (), and if not it will just display the contents of the function. But when binding an event listener to a element, one may not use parenthesis when calling the function and if they are used it will run as soon as the page loads. (same is true when using the setTimeout or SetInterval function).







javascript function syntax function-call






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 24 '18 at 19:14









Patrick Roberts

20.5k33577




20.5k33577










asked Nov 24 '18 at 19:07









Joe StarbrightJoe Starbright

1114




1114








  • 3





    When you're initializing an event listener, or initializing a timeout or interval you're not calling the function. You're passing the function to the framework to be called at a later designated time.

    – Patrick Roberts
    Nov 24 '18 at 19:11











  • So when is the function ever called

    – Joe Starbright
    Nov 24 '18 at 19:14











  • As I already said, it's called by the framework, not by you.

    – Patrick Roberts
    Nov 24 '18 at 19:16











  • Basically, thats how javascript works. It knows to call it by itself

    – Joe Starbright
    Nov 24 '18 at 19:20






  • 1





    @ScottMarcus The DOM (or whatever place where you register the callback) can be said to be a framework

    – Bergi
    Nov 24 '18 at 19:34
















  • 3





    When you're initializing an event listener, or initializing a timeout or interval you're not calling the function. You're passing the function to the framework to be called at a later designated time.

    – Patrick Roberts
    Nov 24 '18 at 19:11











  • So when is the function ever called

    – Joe Starbright
    Nov 24 '18 at 19:14











  • As I already said, it's called by the framework, not by you.

    – Patrick Roberts
    Nov 24 '18 at 19:16











  • Basically, thats how javascript works. It knows to call it by itself

    – Joe Starbright
    Nov 24 '18 at 19:20






  • 1





    @ScottMarcus The DOM (or whatever place where you register the callback) can be said to be a framework

    – Bergi
    Nov 24 '18 at 19:34










3




3





When you're initializing an event listener, or initializing a timeout or interval you're not calling the function. You're passing the function to the framework to be called at a later designated time.

– Patrick Roberts
Nov 24 '18 at 19:11





When you're initializing an event listener, or initializing a timeout or interval you're not calling the function. You're passing the function to the framework to be called at a later designated time.

– Patrick Roberts
Nov 24 '18 at 19:11













So when is the function ever called

– Joe Starbright
Nov 24 '18 at 19:14





So when is the function ever called

– Joe Starbright
Nov 24 '18 at 19:14













As I already said, it's called by the framework, not by you.

– Patrick Roberts
Nov 24 '18 at 19:16





As I already said, it's called by the framework, not by you.

– Patrick Roberts
Nov 24 '18 at 19:16













Basically, thats how javascript works. It knows to call it by itself

– Joe Starbright
Nov 24 '18 at 19:20





Basically, thats how javascript works. It knows to call it by itself

– Joe Starbright
Nov 24 '18 at 19:20




1




1





@ScottMarcus The DOM (or whatever place where you register the callback) can be said to be a framework

– Bergi
Nov 24 '18 at 19:34







@ScottMarcus The DOM (or whatever place where you register the callback) can be said to be a framework

– Bergi
Nov 24 '18 at 19:34














2 Answers
2






active

oldest

votes


















1














It's actually pretty simple once you understand that, in JavaScript, functions are data as well as units of invocable code. That means that you can pass them around, just as if you were passing the number 10 or the string "test".





  • When invoking a function, you must include parenthesis.



    foo(); // Invokes the foo function




  • When referencing a function (as data to be used somewhere), you
    don't. Event callbacks are examples of function referencing. In the following example, the string "click" and the function foo are being passed as arguments (data) to the .addEventListener() method of some element. That element, would now have foo registered in as a callback function to call if/when that element's click event occurs. We don't want to invoke foo right now, we just want to let the element know what function to possibly invoke later.



    element.addEventListener("click", foo); // References foo as the click event callback




    • Now, things can get a bit more complicated because functions can return a value when they are done running and that value (data) can also be another function. In those cases, we want to invoke a function in order to get the function that it returns back (as data):







function returnAfunction(){
// When this function is invoked, it will return
// (as data) another function:
return function(){
console.log("You did it!");
};
}

// Here, notice that the second argument does have parenthesis after it.
// This is because we want the function to run right now and whatever its
// returned value is will then become the actual event callback for the
// button element.
document.querySelector("button").addEventListener("click", returnAfunction());

<button type="button">Click me!</button>








share|improve this answer


























  • Thanx. i just didnt understand that once you referenced it, the framework will call it later automatically like Patrick Roberts pointed out

    – Joe Starbright
    Nov 24 '18 at 19:25






  • 1





    @JoeStarbright That is what .addEventListener() does. It's job is to add an event listener (function) to the element so that when the referenced event (click in this case) occurs, any registered handlers will automatically be invoked. The idea of function referencing is central to how JavaScript operates.

    – Scott Marcus
    Nov 24 '18 at 19:26



















0














I think it is because when you define a function, you may pass it some parameters like



const isUserValid = (username, password) => {
for (i = 0; i < database.length; i++) {
if (database[i].username === username && database[i].password === password) {
return true;
}
}
return false;
}


and so is true for when you want to execute the function. But when you add an event listener, then you are automatically calling the function to execute on (i.e. click)






share|improve this answer

























    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53461500%2fwhen-exactly-is-parenthesis-needed-when-executing-a-function%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    1














    It's actually pretty simple once you understand that, in JavaScript, functions are data as well as units of invocable code. That means that you can pass them around, just as if you were passing the number 10 or the string "test".





    • When invoking a function, you must include parenthesis.



      foo(); // Invokes the foo function




    • When referencing a function (as data to be used somewhere), you
      don't. Event callbacks are examples of function referencing. In the following example, the string "click" and the function foo are being passed as arguments (data) to the .addEventListener() method of some element. That element, would now have foo registered in as a callback function to call if/when that element's click event occurs. We don't want to invoke foo right now, we just want to let the element know what function to possibly invoke later.



      element.addEventListener("click", foo); // References foo as the click event callback




      • Now, things can get a bit more complicated because functions can return a value when they are done running and that value (data) can also be another function. In those cases, we want to invoke a function in order to get the function that it returns back (as data):







    function returnAfunction(){
    // When this function is invoked, it will return
    // (as data) another function:
    return function(){
    console.log("You did it!");
    };
    }

    // Here, notice that the second argument does have parenthesis after it.
    // This is because we want the function to run right now and whatever its
    // returned value is will then become the actual event callback for the
    // button element.
    document.querySelector("button").addEventListener("click", returnAfunction());

    <button type="button">Click me!</button>








    share|improve this answer


























    • Thanx. i just didnt understand that once you referenced it, the framework will call it later automatically like Patrick Roberts pointed out

      – Joe Starbright
      Nov 24 '18 at 19:25






    • 1





      @JoeStarbright That is what .addEventListener() does. It's job is to add an event listener (function) to the element so that when the referenced event (click in this case) occurs, any registered handlers will automatically be invoked. The idea of function referencing is central to how JavaScript operates.

      – Scott Marcus
      Nov 24 '18 at 19:26
















    1














    It's actually pretty simple once you understand that, in JavaScript, functions are data as well as units of invocable code. That means that you can pass them around, just as if you were passing the number 10 or the string "test".





    • When invoking a function, you must include parenthesis.



      foo(); // Invokes the foo function




    • When referencing a function (as data to be used somewhere), you
      don't. Event callbacks are examples of function referencing. In the following example, the string "click" and the function foo are being passed as arguments (data) to the .addEventListener() method of some element. That element, would now have foo registered in as a callback function to call if/when that element's click event occurs. We don't want to invoke foo right now, we just want to let the element know what function to possibly invoke later.



      element.addEventListener("click", foo); // References foo as the click event callback




      • Now, things can get a bit more complicated because functions can return a value when they are done running and that value (data) can also be another function. In those cases, we want to invoke a function in order to get the function that it returns back (as data):







    function returnAfunction(){
    // When this function is invoked, it will return
    // (as data) another function:
    return function(){
    console.log("You did it!");
    };
    }

    // Here, notice that the second argument does have parenthesis after it.
    // This is because we want the function to run right now and whatever its
    // returned value is will then become the actual event callback for the
    // button element.
    document.querySelector("button").addEventListener("click", returnAfunction());

    <button type="button">Click me!</button>








    share|improve this answer


























    • Thanx. i just didnt understand that once you referenced it, the framework will call it later automatically like Patrick Roberts pointed out

      – Joe Starbright
      Nov 24 '18 at 19:25






    • 1





      @JoeStarbright That is what .addEventListener() does. It's job is to add an event listener (function) to the element so that when the referenced event (click in this case) occurs, any registered handlers will automatically be invoked. The idea of function referencing is central to how JavaScript operates.

      – Scott Marcus
      Nov 24 '18 at 19:26














    1












    1








    1







    It's actually pretty simple once you understand that, in JavaScript, functions are data as well as units of invocable code. That means that you can pass them around, just as if you were passing the number 10 or the string "test".





    • When invoking a function, you must include parenthesis.



      foo(); // Invokes the foo function




    • When referencing a function (as data to be used somewhere), you
      don't. Event callbacks are examples of function referencing. In the following example, the string "click" and the function foo are being passed as arguments (data) to the .addEventListener() method of some element. That element, would now have foo registered in as a callback function to call if/when that element's click event occurs. We don't want to invoke foo right now, we just want to let the element know what function to possibly invoke later.



      element.addEventListener("click", foo); // References foo as the click event callback




      • Now, things can get a bit more complicated because functions can return a value when they are done running and that value (data) can also be another function. In those cases, we want to invoke a function in order to get the function that it returns back (as data):







    function returnAfunction(){
    // When this function is invoked, it will return
    // (as data) another function:
    return function(){
    console.log("You did it!");
    };
    }

    // Here, notice that the second argument does have parenthesis after it.
    // This is because we want the function to run right now and whatever its
    // returned value is will then become the actual event callback for the
    // button element.
    document.querySelector("button").addEventListener("click", returnAfunction());

    <button type="button">Click me!</button>








    share|improve this answer















    It's actually pretty simple once you understand that, in JavaScript, functions are data as well as units of invocable code. That means that you can pass them around, just as if you were passing the number 10 or the string "test".





    • When invoking a function, you must include parenthesis.



      foo(); // Invokes the foo function




    • When referencing a function (as data to be used somewhere), you
      don't. Event callbacks are examples of function referencing. In the following example, the string "click" and the function foo are being passed as arguments (data) to the .addEventListener() method of some element. That element, would now have foo registered in as a callback function to call if/when that element's click event occurs. We don't want to invoke foo right now, we just want to let the element know what function to possibly invoke later.



      element.addEventListener("click", foo); // References foo as the click event callback




      • Now, things can get a bit more complicated because functions can return a value when they are done running and that value (data) can also be another function. In those cases, we want to invoke a function in order to get the function that it returns back (as data):







    function returnAfunction(){
    // When this function is invoked, it will return
    // (as data) another function:
    return function(){
    console.log("You did it!");
    };
    }

    // Here, notice that the second argument does have parenthesis after it.
    // This is because we want the function to run right now and whatever its
    // returned value is will then become the actual event callback for the
    // button element.
    document.querySelector("button").addEventListener("click", returnAfunction());

    <button type="button">Click me!</button>








    function returnAfunction(){
    // When this function is invoked, it will return
    // (as data) another function:
    return function(){
    console.log("You did it!");
    };
    }

    // Here, notice that the second argument does have parenthesis after it.
    // This is because we want the function to run right now and whatever its
    // returned value is will then become the actual event callback for the
    // button element.
    document.querySelector("button").addEventListener("click", returnAfunction());

    <button type="button">Click me!</button>





    function returnAfunction(){
    // When this function is invoked, it will return
    // (as data) another function:
    return function(){
    console.log("You did it!");
    };
    }

    // Here, notice that the second argument does have parenthesis after it.
    // This is because we want the function to run right now and whatever its
    // returned value is will then become the actual event callback for the
    // button element.
    document.querySelector("button").addEventListener("click", returnAfunction());

    <button type="button">Click me!</button>






    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited Nov 24 '18 at 19:40

























    answered Nov 24 '18 at 19:17









    Scott MarcusScott Marcus

    39.4k52038




    39.4k52038













    • Thanx. i just didnt understand that once you referenced it, the framework will call it later automatically like Patrick Roberts pointed out

      – Joe Starbright
      Nov 24 '18 at 19:25






    • 1





      @JoeStarbright That is what .addEventListener() does. It's job is to add an event listener (function) to the element so that when the referenced event (click in this case) occurs, any registered handlers will automatically be invoked. The idea of function referencing is central to how JavaScript operates.

      – Scott Marcus
      Nov 24 '18 at 19:26



















    • Thanx. i just didnt understand that once you referenced it, the framework will call it later automatically like Patrick Roberts pointed out

      – Joe Starbright
      Nov 24 '18 at 19:25






    • 1





      @JoeStarbright That is what .addEventListener() does. It's job is to add an event listener (function) to the element so that when the referenced event (click in this case) occurs, any registered handlers will automatically be invoked. The idea of function referencing is central to how JavaScript operates.

      – Scott Marcus
      Nov 24 '18 at 19:26

















    Thanx. i just didnt understand that once you referenced it, the framework will call it later automatically like Patrick Roberts pointed out

    – Joe Starbright
    Nov 24 '18 at 19:25





    Thanx. i just didnt understand that once you referenced it, the framework will call it later automatically like Patrick Roberts pointed out

    – Joe Starbright
    Nov 24 '18 at 19:25




    1




    1





    @JoeStarbright That is what .addEventListener() does. It's job is to add an event listener (function) to the element so that when the referenced event (click in this case) occurs, any registered handlers will automatically be invoked. The idea of function referencing is central to how JavaScript operates.

    – Scott Marcus
    Nov 24 '18 at 19:26





    @JoeStarbright That is what .addEventListener() does. It's job is to add an event listener (function) to the element so that when the referenced event (click in this case) occurs, any registered handlers will automatically be invoked. The idea of function referencing is central to how JavaScript operates.

    – Scott Marcus
    Nov 24 '18 at 19:26













    0














    I think it is because when you define a function, you may pass it some parameters like



    const isUserValid = (username, password) => {
    for (i = 0; i < database.length; i++) {
    if (database[i].username === username && database[i].password === password) {
    return true;
    }
    }
    return false;
    }


    and so is true for when you want to execute the function. But when you add an event listener, then you are automatically calling the function to execute on (i.e. click)






    share|improve this answer






























      0














      I think it is because when you define a function, you may pass it some parameters like



      const isUserValid = (username, password) => {
      for (i = 0; i < database.length; i++) {
      if (database[i].username === username && database[i].password === password) {
      return true;
      }
      }
      return false;
      }


      and so is true for when you want to execute the function. But when you add an event listener, then you are automatically calling the function to execute on (i.e. click)






      share|improve this answer




























        0












        0








        0







        I think it is because when you define a function, you may pass it some parameters like



        const isUserValid = (username, password) => {
        for (i = 0; i < database.length; i++) {
        if (database[i].username === username && database[i].password === password) {
        return true;
        }
        }
        return false;
        }


        and so is true for when you want to execute the function. But when you add an event listener, then you are automatically calling the function to execute on (i.e. click)






        share|improve this answer















        I think it is because when you define a function, you may pass it some parameters like



        const isUserValid = (username, password) => {
        for (i = 0; i < database.length; i++) {
        if (database[i].username === username && database[i].password === password) {
        return true;
        }
        }
        return false;
        }


        and so is true for when you want to execute the function. But when you add an event listener, then you are automatically calling the function to execute on (i.e. click)







        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Nov 24 '18 at 19:26









        Patrick Roberts

        20.5k33577




        20.5k33577










        answered Nov 24 '18 at 19:18







        user10697029





































            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53461500%2fwhen-exactly-is-parenthesis-needed-when-executing-a-function%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Ottavio Pratesi

            Tricia Helfer

            15 giugno