# Callbacks
# What are they?
What Are javascript callbacks: A callback is a function passed as an argument to another function. This technique allows a function to call another function later or immediately the current function has been executed.
//Defining functions
function prepare(ingredients, callback) {
console.log("Preparing " + ingredients);
callback();
}
//callback function
function chop() {
console.log("Chopping");
}
//Calling the function
prepare("onions and garlic", chop);
Most of the time developers won’t write functions like you see in the example, they will put it directly as an argument to keep the code clean.
//Defining function
function prepare(ingredients, callback) {
console.log("Preparing " + ingredients);
callback();
}
//Calling the function
prepare("onions and garlic", function chop() {
console.log("Chopping");
});
You can also pass down arguments in the callback function for any usage you want:
//Defining function
function prepare(ingredients, callback) {
console.log("Preparing " + ingredients);
callback(ingredients); //this time, ingredients is added as an argument for the callback
}
//Calling the function
prepare("onions and garlic", function chop(arg) { //chop() now takes in arg as an argument
console.log("Chopping " + arg);
});
The above function is a synchronous function as it’s executed immediately.
# Asynchronous Javascript Callback Functions
As stated above, there are two types of callback functions, we have discussed synchronous callbacks, now let’s view asynchronous callbacks. These types of callbacks functions are used to start executing tasks in the background while the function keeps running.
# Example with setTimeout
const fn = () => {
let x = "middle";
console.log("start");
setTimeout(() => console.log(x));
console.log("finished");
}
fn();
// "start"
// "finished"
// "setTimeout result"
Here we can see the usage of setTimeout; an asynchronous callback function that the browser API lets us use (later on you will know more about browser API). This function will be executed in the background and it won’t wait until the other pieces of code are executed. As you can see in the example above, our console.log's order will be:
1)start
2)finished
3)setTimeout result
Because the two first console.log's are synchronous, they will execute immediately and they won’t wait for the result of the asynchronous function setTimeout to finish.