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

window.onload = initAll();

This executes initAll() straight away and assigns the function’s return value to window.onload. This is usually not what you want. initAll() would have to return a function for this to make sense.

window.onload = initAll;

this assigns the actual function to window.onload – this is possible because in JavaScript, as @Felix says, functions are first class objects – without executing it. initAll will be executed by the load event.

You may also see something like this:

window.onload = () => initAll();

This will create a new function that, when called, will call initAll immediately. Parentheses are necessary here for that “call initAll immediately” part to work. But, because it’s wrapped in a function, nothing will execute until that outer function itself is called, and you assign the reference of that outer function to window.onload, so initAll will also be executed on the load event.

Leave a Comment