Callbacks In JavaScript😝

Introduction

In this article, we are going to learn about Callbacks in JavaScript.

Before getting into callbacks let's understand synchronous and asynchronous behavior in programming.

ASYNC & SYNC BEHAVIOUR

Let us try to understand the difference between synchronous and asynchronous behavior in programming.

Synchronous way means to let you have two lines of code (A followed by B), then B cannot begin to execute until A has finished executing. Synchronous code always behaves like a queue of processes and before a certain process finishes, the next process cannot start running.

In Asynchronous programs, you can have two lines of code where the second line of code can execute even before the first line of code finishes. This can be achieved in Javascript with "callbacks" and "promises".

When Callbacks, meet closures, the magic of letting multiple things run all at the same time.

One of the most basic ways to utilize the async in JavaScript is through the setTimeut function.

Basically the setTimeout() function allows code to be executed after some trigger, or after a certain amount of time. The amount of time after which we want a certain piece of code to execute has to be specified within the setTimeout function and has to be specified in milliseconds.

console.log("Begin...");
setTimeout(function() {
    console.log("After 3 seconds...");
}, 3000);
console.log("End...");

Here, the first line of the code executes first and prints “Begin…” on the console. the compiler encounters the second line of the code which is the setTimeout function in the above code. It tells the compiler to wait for 3000 milliseconds (3 seconds) until this console statement executes (“After 3 seconds…”). The compiler moves on to print the last console statement “End…” even before the second one because Javascript does not wait for the second console statement to complete. The second console statement prints after a gap of 3000 milliseconds.

Let's understand the most important concept in Callbacks.

A callback is a function that is passed into another function as an argument, which is then invoked inside the outer function to complete an action. 

Let assume here you want to write a simple function that would prompt the user to type in the kind of tea he/she would like to have, and based on her response, display an alert or a prompt saying that her choice of tea is being prepared.

Here we can write a simple callback function for this.

function teaMachine(name) {
    alert("Preparing " + name);
}
function prepare(callback) {
    var name = prompt("What tea would you like to have? Iced Tea or Green Tea?");
    callback(name);
}
prepare(teaMachine);

Here the function “teaMachine serves as our callback function. This callback function (“teaMachine”) is passed as an argument into the “prepare” function in the last line. What is happening is that when the “prepare” function is called, it prompts the user to type in his tea of choice. When the user finishes typing, the callback function is called with “name” as the parameter. Note that “name” consists of whatever tea name the user may have typed (Ice Tea, Green Tea, and so on). Finally the callback function “teaMachine” is called which displays an alert “Preparing <name>”, where <name> is the tea name input that the user-provided. One noteworthy point here is that callback functions are possible because functions are first-class citizens in JS and can be passed around like objects as parameters to other functions

The above example is the synchronous callback, as the callback function is executed only after the code finishes execution. Callbacks can also be used to accomplish async operations.

Most importantly JavaScript is an event-driven language. Event-Driven means that instead of waiting for a response before moving on, JavaScript will keep executing while listening for other events.

Callbacks are a way to ensurethat certain code does not execute until another code has already finished executing.

We can create a callback function that we pass to an asynchronous function, which will be called when the task is finished.

In the Next blog, we are going to learn about Promises in JavaScript and how async operations work in Javascript.

That's all about Callbacks in JavaScript.

Happy Reading