javascript – Why should we use anonymous functions with jQuery instead of the function directly?


I have a doubt, some jQuery methods expect a function as a parameter, but to work they must receive an inner function as a parameter instead of a function directly, as in the example below:

$("a").on("click", function() { retornaNada(); });

rather than

$("a").on("click", retornaNada());

Consider retornaNada() as a function of any type without a code body. Why can't we pass the function directly?


Methods that expect a function expect a reference to the function. For example:

$("a").on("click", retornaNada); 

This is advantageous if you want to use the same function as an event handler in more than one place. For example:

$("a").on("click", retornaNada); 
$("span").on("click", retornaNada); 

Passing in anonymous roles, you would need to create two different roles.

Now notice that what you did was:

$("a").on("click", retornaNada()); 
//                  ----------^^

You called the function, and actually passed its return value as handler. Since retornaNada returns nothing, including the parentheses means the same as:

$("a").on("click", undefined);

That's why it doesn't work.

Scroll to Top