Skip to content Skip to sidebar Skip to footer

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 'parame

Solution 1:

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.


Solution 2:

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.


Post a Comment for "Are Functions Passed As Parameters Always Callbacks? JavaScript"