Edwin
Edwin

Reputation: 181

Callback function - use of parentheses

I'm new to jQuery and am bit confused about the use (or not) of parentheses with a callback function. Say I have a function:

function cb() {
 // do something
}

Now what is the difference between:

$("p").hide(1000, cb);

and

$("p").hide(1000, cb());

Is it to do with when the cb function is executed? It would be great if someone could explain this to me in the simplest of terms.

Upvotes: 18

Views: 3525

Answers (4)

Michael
Michael

Reputation: 4090

cb() means give me the result of executing the function cb.

cb IS the function cb or, more accurately a pointer (reference) to it.

Upvotes: 13

Dunes
Dunes

Reputation: 40703

The difference is that in javascript functions are first class objects and can be passed to other functions so that they may executed at a later stage or depending on some logic.

Consider the following:

function add(a, b) {
    return a + b;
}

function minus(a, b) {
    return a - b;
}

function apply(func, a, b) {
    return func(a,b);
}

apply(add, 3, 4); // returns 7
apply(minus, 3, 4); // returns -1

apply(add(), 3, 4); // error: invalid number of arguments for add

apply(add(0,0), 3, 4); // error: add returns 0, but 0 is not a function and 
// so apply crashes when it tried to call zero as a function

Upvotes: 4

Dan Lugg
Dan Lugg

Reputation: 20592

$("p").hide(1000, cb); passes the function referenced by cb, as a callback.

$("p").hide(1000, cb()); passes the value returned when the function cb is called.

Given:

function cb(){ return true; }

The former is passing the callback for later calling. The latter passes the returned value true, and is essentially $("p").hide(1000, true);

Upvotes: 3

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385144

Is it to do with when the cb function is executed?

Essentially, yes, though the difference does run a little deeper than that.

  • cb is a reference of sorts to the function. You're passing the function along as a parameter to be invoked somewhere down the line.

  • cb() is a function call; the function will be invoked, and the result passed as an argument to .hide.

Upvotes: 8

Related Questions