Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are functions passed as parameters always callbacks? JavaScript

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;
});
like image 981
Zach Smith Avatar asked Mar 16 '23 18:03

Zach Smith


2 Answers

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.

like image 153
Alnitak Avatar answered Apr 25 '23 21:04

Alnitak


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.

like image 21
6502 Avatar answered Apr 25 '23 21:04

6502