What is a Callback? - JavaScript

Callback function is a function that is to be executed after another function has finished executing.
So let's take a function that takes a function as an argument.This is possible because JS consider's functions as objects.So any function that is passed as an argument is called a Callback function.Now let's look at some examples.

So why do we need Callbacks? You might already know that Java Script is an event driven language.This means that Java Script does not wait for responses from any event that takes time like I/O operations, Instead it keeps executing the code while listening to other events.This becomes a problem sometimes.Let's see why




The output of this function will be 1,2 in order respectively as expected.

No problem here.But what if the first function takes some time to execute?Like an API request that needs to wait for a response from the server.Let's look at an example related to this scenario.To do this we're going to use the function set Timeout and delay our function by 500 milliseconds time instead of calling an actual API request.



Here the answer will be 2 and 1 in order respectively.So even though we have called the first() function first the answer of the second() function will be showed first.This simply happens because of how Java Script works.As stated before Java Script does not wait for any operations to complete it simply starts executing whatever code that is available after that function while listening to the events that takes time.

So what's the problem with this? Let's look at the above example.What if we want to execute the second function after the first one has been executed?which means that the second function cannot be executed properly without the response from the first function.How can we do this? We can simply use Callbacks to solve this problem.Let's see how.



As you can see the second function is given as a parameter to first function.Here the second operation will only be executed after the first operation has been completed.



So as you can see giving the second function as a callback to the first solves the problem we had.

That's it guys! Thanks for reading.




















Comments

Popular posts from this blog

Difference between var,const and let in JavaScript

Introduction to NODE.JS