If I have the code below, where I pass two functions as a parameters into the function sayHi
, is this an example of a callback?
I notice there are two ways of running these 'parameter functions': either as below, we I call the functions where they are defined (as arguments), or alternatively where I call the parameter in the sayHi function. Would this be the difference between a callback and an anonymous function?
function sayHi(name, testForTrue) {
if (testForTrue == true) {
console.log(name);
}
}
sayHi(function() {
return 'Zach'
}(), function() {
return true;
}());
Another way I could get the same result, is as below. In this case I am evaluating the functions at a different time? Is there any practical difference between the two?
function sayHi(name, testForTrue) {
if (testForTrue() == true) {
console.log(name());
}
}
sayHi(function() {
return 'Zach'
}, function() {
return true;
});
Yes, functions passed as parameters are always callbacks, even if the intention is that the function is called synchronously (c.f. Array.prototype.map
) rather than asynchronously (c.f. window.setTimeout
).
In your first code block you aren't of course actually passing functions. You have two immediately invoked function expressions, where the key part in this context is immediately invoked. The function expressions are called at the point they appear in the code and only the results of those expressions are passed to sayHi
.
In your first example you're not passing functions, but values; in other words
(function(){ return 3; })()
is just the integer 3.
It is a value obtained calling immediately a function, but this is irrelevant.
When you pass a callback it's the receiver that will call it (or pass it to some other function) and the code will be executed later, and not at the call site.
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