Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 204
Edwin Avatar asked Jul 05 '11 22:07

Edwin


People also ask

Why do we use parentheses in JavaScript?

In JavaScript we only write a value in the parentheses if we need to process that value. Sometimes the purpose of the function is to perform a task rather then process some kind of input. Examples: var sayHello = function() { console.

What are callback functions with an example?

A callback function is a function passed into another function as an argument, which is then invoked inside the outer function to complete some kind of routine or action. The above example is a synchronous callback, as it is executed immediately.

Does return need parentheses JavaScript?

Never return something on a new line without using parentheses. This is a JavaScript quirk and the result will be undefined. Try to always use parentheses when returning something on multiple lines.

When would you use a callback function?

Need of Callback Functions. We need callback functions because many JavaScript actions are asynchronous, which means they don't really stop the program (or a function) from running until they're completed, as you're probably used to. Instead, it will execute in the background while the rest of the code runs.


2 Answers

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

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

like image 96
Michael Avatar answered Sep 16 '22 11:09

Michael


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.

like image 29
Lightness Races in Orbit Avatar answered Sep 17 '22 11:09

Lightness Races in Orbit