Callbacks in JavaScript

Aniketchanana
3 min readJun 7, 2020

JavaScript is a single-threaded language which means you can only run one process at a time

But wait what if some process is taking too long to execute for example a code that is making a request to the server for getting data like this.

let xhr = new XMLHttpRequest();
xhr.open(“GET”, “URL”, true);
xhr.send();.

if JavaScript is a single-threaded language then it should block the code and wait for the response. But this is not the case javascript does not block the entire execution of code written after. So the question here arises is that what is the trick javascript uses in order to run this code.

What is a callback function?
callback functions are justa like like normal functions in javascript the only thing which makes them different from a normal function is that they are passed as an argument to a function.

function getData(filename,callback) {
// file read code
//after the file read is done callback function is called with or without argument which indicates that file read operation is done
callback(‘data’);
}

why do we need callback functions?
As discussed in starting javascript is a single-threaded language so it has only one main thread to perform an operation and if some block of code is taking too long to execute then it will block the main thread. in this kind of scenario we use callback functions which are passed as an argument and once the work is done then that callback function is called with required data are parameter to the function.

let xhr = new XMLHttpRequest();
xhr.open("GET", "URL", true);
xhr.send();
xhr.addEventListener('load',function(){
if (this.status === 200 && this.readyStateChange === 4){
console.log(JSON.parse(xhr.responseText);
}
});

In this code, we have passed attached an event listener to with our HTTP request so every time our HTTP request is loaded our callback function is called every time and the code inside the callback function will run.

How to create a callback function?
It is very simple to create callback functions you just need to pass a function as an argument to other function and call it inside that function with or without parameter according to your need.
Follow the below steps in order to create your own callback.

Create a function which takes another function as argument

function add(a, b, callBack) {
let ressult = a+b;
callBack(result);
}

Create a function which you can pass to the above function

This is like any other normal javascript function

function printResult(result) {
console.log(result);
}

Now call the add function with print result function as argument

add(10, 20, printResult);

Output for the above code will be

If you found this post helpful please drop a like ❤ thank you for reading and stay tuned for such posts

--

--