Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

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 wondered, what would be the difference between:

window.onload = initAll(); 

and

window.onload = initAll; 

Please explain the principle behind it.

like image 335
Dean Avatar asked Jul 14 '10 14:07

Dean


People also ask

What is the difference between calling function with parentheses and without in JavaScript?

With parenthesis the method is invoked because of the parenthesis, the result of that invocation will be stored in before_add. Without the parenthesis you store a reference (or "pointer" if you will) to the function in the variable. edit: Added as answer which should be more appropriate. Does this answer your question?

What does parentheses do in JavaScript?

In JavaScript, the functions wrapped with parenthesis are called “Immediately Invoked Function Expressions" or "Self Executing Functions. The purpose of wrapping is to namespace and control the visibility of member functions. It wraps code inside a function scope and decrease clashing with other libraries.

Can I call function without parentheses in JavaScript?

Calling a JavaScript function without the parens passes that function's definition as a reference. It is one of the fundamentals to programming in JavaScript known as callbacks.

When you call a function with a value in the parenthesis you are?

When we call a function with parentheses, the function gets execute and returns the result to the callable. In another case, when we call a function without parentheses, a function reference is sent to the callable rather than executing the function itself.


1 Answers

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.

like image 153
Pekka Avatar answered Oct 25 '22 23:10

Pekka