Take the 2-minute tour ×

Let's say I have a function:

function myFunction() {

I want to call it from event handler. Why this construction doesn't call my function?


But this does the trick:


What is the difference between these types of calling?

share|improve this question

1 Answer 1

up vote 9 down vote accepted

immediately calls myFunction and passes the return value to resize. Adding parenthesis after a function name/reference calls the function.

On the other hand,


passes an anonymous function to resize. myFunction is only called when the outer function is called.

Anonymous functions are nothing special. In this case it is just some kind of inline function definition. You can easily replace it with a function reference:

var handler = function(){myFunction()}; // take out the function definition
$(window).resize(handler);  // and replace it with the new name

Now you can see that there are no parenthesis after the function name, which means, handler is not called, only the reference is passed.

I hope you can also see now that creating a new function in this example is not necessary. You can achieve the same by simply passing a reference to myFunction:


But both ways have their use cases.

The first example $(window).resize(myFunction()); can still be useful if myFunction returns a function that should be used as event handler:

function myFunction() {
    var handler = function() {};
    return handler;

Maybe the handler retuned depends on a parameter passed to myFunction.

Passing an anonymous function is necessary if you want to call myFunction with some specific arguments:

function myFunction(a, b) {
    alert(a + b);

    myFunction(40, 2);


@T.J. Crowder made an important comment about the event object. Every event handler gets the event object passed as first parameter. If you'd define your function as

function myFunction(event) {

to have (easier) access to it, using an anonymous function, you would have to pass it through:


if you want to use it.

share|improve this answer
"You can achieve the same by only passing a reference to myFunction:" It's slightly different. In that case, myFunction will receive the event argument, whereas with his/her $(window).resize(function(){myFunction()}); version, myFunction doesn't see the event argument. –  T.J. Crowder Jun 26 '11 at 10:35

Your Answer


