Javascript Callback Function

What is a callback function?

A callback is a function which will be executed once after a particular task or function has finished its execution.

Why do we need callback?

Since javascript is asynchronous in nature, it will execute asynchronous task in parallel. It means that it will not wait until the task is completed. But user may be in a need to perform some operation once the asynchronous task gets completed. At this scenario, callback comes into action.

Let's see it with a simple example program.



The above program is a simple example for callback function. Here add() function is a function which consist of 3 arguments. First and second arguments are values and the third argument is a function.

The add function, adds the value of 'a' & 'b' and holds it in a constant variable 'result'. Now it calls the callback function with 'result' as parameter. Here printResult() function is passed as the callback function. Now the code in printResult() function will be executed which in return prints the value obtained as an argument.

Let see another program to read a file and print its content.


Program execution completed.
This is the file content.

The above code is a simple example for callback. Here we use 'fs' npm which is used for performing file operation. Now the constant variable 'fs' holds the function needed to perform operations on the file. The 'readFile' is one of the functions that can reads a file and contains 2 arguments. First argument is theurl of a file and the second argument is a function with 2 argument which will be called once after the file is read. The function which acts as the second argument is the callback function.

The callback function will have 2 arguments, First argument is the error object which holds error if any error occurred when reading the file and the second argument is the buffer data for the file that is read.

If we observe the output before the content of the file is printed,'Program execution completed.' Will be printed. This is because when reading the file content, the main thread won't wait for it to complete but instead it will start executing the next line. Now, once the file has been read the callback function will display the file content.

To summarize the topic, callback function is a function that will be called back after a task has been completed.

Most Read