Use of Callback in javascript

What is callback? What is the need for a callback? Synchronous Asynchronous Callback Hell

What is a callback?

It is a function that is passed as argument to another function. It is executed once the main function has finished executing. A callback function invokes in the main function to perform actions asynchronously.

What is the need for a callback?

Callbacks can be used for various tasks in programming, such as event handling, network requests, and user interactions. It is a powerful tool for writing clean and efficient code. It is used to execute code after a certain task has been completed.

The callback is used for various aspects:

  1. Handling Asynchronous Operations:

    When we are dealing with the asynchronous operation, we cannot wait for the operation to complete. We can register a callback function to handle the response when executing.

  2. Event Handling:

    When we handle user events such as clicking on the button, or double clicking on the button, we can register a callback function to be executed when the event occurs.

  3. Requests to API:

    When a function connects from an API to fetch data, all files must be get downloaded before function execution. We use the callback function so that the function that needs the data will only get executed when all the required data is downloaded. By the defined callback, we can prevent running into errors.

Callback functions can be used in two scenarios:

  1. Synchronous operations.

  2. Asynchronous operations.

What is synchronous?

In general meaning, synchronous is a same-time operation. For example, If you make a call to any person, you will find a response from another person at the same time.

Synchronous refers to real-time communication where each party receives messages instantly.

In programming meaning, many programming commands are also synchronous. For example, when you give inputs in a calculation, the environment will return the result to you instantly, unless you program it not to.

Use of callback functions in synchronous

Here is a example of callback, which is passing to other function.

In the above code, program starts with logging 'start'. After logging 'start', function1 and function2 are defined. When function2 calls function1 as a callback, function 1 is executed within the function2. After executing callback function2 logs console.log's text.At last, console syntax logs 'end'.

What is asynchronous?

Asynchronous communication is a method of exchanging messages between two or more parties in which each party receives and processes messages whenever it's convenient or possible to do so. For humans, email is an asynchronous communication method. The sender sends an email and the recipents will read and reply to the message when it's convient to do so, rather than doing so at once.

The asynchronous refers to two or more objects or events not existing or happening at the same time.

In programming, asynchronous allows to make operations successful after some time. and it also makes possible to execute code in jump mode not sequentially.

Nested callbacks

When a callback function is called inside another callback function, it is called nested callback in asynchronous programming.

This pattern is used when you need to execute a series of asynchronous tasks, where each task depends on the output of the previous task.

In this program, setTimeout uses every time a callback function. It is example of nested callback. The first callback function is executed completely in 3 seconds.

Example of the callback function

Let's look at an example of a callback.

We are making a program of squares of any number.

//function to find the square of a number

function square(num){

console.log(num*num)

}

//passing callback

function operation(num, callbackfunc){

callbackfunc(num);

}

// calling the function

operation(5, square); //output:25

In the above program, square is a function with a parameter num to find the square of any number. operation is the function which is passing two arguments, first is num (a number) and the second is a callback function (callbackfunc). After executing the code, it gives 25 numbers as an output, when we pass the number 5.

Callback Hell

Callbck hell is a situation in asynchronous programming where multiple levels of nested callbacks make the code difficult to read, usderstand, and maintain. This can occur when you have to execute a series of asynchronous tasks, where each task depends on the output of the previous task, and you need to pass the results of each task to the next one.

If we use a lot of nested callbacks, the code can be difficult to read and maintain. In this case, searching of occured errors become difficult. To avoid callback hell, some techniques are used like promises, async/await.

Did you find this article valuable?

Support WebIndia by becoming a sponsor. Any amount is appreciated!