Callback functions are common in JavaScript. Callback functions are possible in JavaScript because functions are first-class citizens.
Callback functions can be synchronous or asynchronous. Since Asynchronous callback functions may be more complex here is a simple example of a synchronous callback function.
// a function that uses a callback named `cb` as a parameter
function getSyncMessage(cb) {
cb("Hello World!");
}
console.log("Before getSyncMessage call");
// calling a function and sending in a callback function as an argument.
getSyncMessage(function(message) {
console.log(message);
});
console.log("After getSyncMessage call");
The output for the above code is:
> Before getSyncMessage call
> Hello World!
> After getSyncMessage call
First we will step through how the above code is executed. This is more for those who do not already understand the concept of callbacks if you do already understand it feel free to skip this paragraph. First the code is parsed and then the first interesting thing to happen is line 6 is executed which outputs Before getSyncMessage call
to the console. Then line 8 is executed which calls the function getSyncMessage
sending in an anonymous function as an argument for the parameter named cb
in the getSyncMessage
function. Execution is now done inside the getSyncMessage
function on line 3 which executes the function cb
which was just passed in, this call sends an argument string “Hello World” for the param named message
in the passed in anonymous function. Execution then goes to line 9 which logs Hello World!
to the console. Then the execution goes through the process of exiting the callstack (see also) hitting line 10 then line 4 then finally back to line 11.
Some information to know about callbacks in general:
message
could have been named statement
, msg
, or if you’re being nonsensical something like jellybean
. So you should know what parameters are sent into your callback so you can get them in the right order with proper names.One thing to note about JavaScript is it is synchronous by default, but there are APIs given in the environment (browser, Node.js, etc.) that could make it asynchronous (there’s more about that here).
Some common things that are asynchronous in JavaScript environments that accept callbacks: