Search code examples
javascriptfunctionevent-handling

Difference between assigning event handler to method with and without parentheses


Assuming you have the following:

function doStuff() {
  //code
}

What is the the difference between the 2 statements ?

window.onload = doStuff;

window.onload = doStuff();

Both statements seemed to immediately call the method, but if I used the first statement, I could treat onload as a function pointer to "doStuff" and just call the method again using:

onload();

Is this the only difference, and in general, is this all guaranteed behavior for event handlers ?


Solution

  • You're actually a bit off in your understanding.

    window.onload = doStuff;
    

    means that when the onload event is triggered, the doStuff function will be called.

    window.onload = doStuff();
    

    means that when that line of code is reached (before the onload event is triggered), doStuff is executed and it's return result is assigned to the onload handler.

    You probably want the first one unless doStuff returns a function to be executed when the onload event is triggered.