Kameswaran Ganesh Kameswaran Ganesh - 3 months ago 8
jQuery Question

jQuery- how .click() works with function identifier passed as argument?

$('button').click(function(){ console.log('works'); });


This outputs 'works' when I click the required button.

But if I pack the same code in a function and call it with parentheses attached to it(as you usually invoke a function), as in

function worker(){ console.log('works'); }
$('button').click(worker());


worker gets fired without any click on button. But if I avoid the parentheses, as in

function worker(){ console.log('works'); }
$('button').click(worker);


I'm getting the desired functionality. Why the click handler behaves this way?

Answer

When you call a function in JavaScript without parenthesis, what you are doing is assigning the actual function. This does not immediately execute the function.

When you call a function in JavaScript with parenthesis, you are executing the function immediately and returning the value of that function.

Having said that, if you had a function that returned a function itself, you could in-fact call a function, whose return value would then be another function. (Generally not advised)

To address your comment: Suppose you write the following statement: $('button').click(console.log('works'); The result would be that as soon as your page is loaded, "works" will be printed to the console. This is because console.log() is a function being called with parenthesis.

However, if you did the following approach:

var worksFunc = function() {console.log('works')};
$('button').click(worksFunc);

It will now reference the function for execution on the click event.

DEMO

Comments