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.
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.
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.
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.
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.
cb()
means give me the result of executing the function cb.
cb
IS the function cb or, more accurately a pointer (reference) to it.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With