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
.