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
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.
I guess that would depend on what your callback function is actually doing.
In your examples, all you're really doing is returning a value. That's not really a "function", it's returning one fixed value every single time.
If your function is actually doing a process, or returning a varied result, then I would personally consider it a callback. (The name of it is self-explanatory, really). Your script shouldn't rely on it, rather have it be a handler for the result of the function.
For instance, something like this would be what I consider a callback function:
With this provided, we can call it like this: