JavaScript CallBack Functions

JavaScript CallBack Functions

What is a CallBack Function?

If you don't know what is a callback function, and you know what is a function, then you know that a function takes in variables ( numbers, strings, boolean, ... etc ) as arguments, now you need to know that besides variables, a function can also take another function as an argument. this another function is what we call a callback function.

So any function that is passed to another function as an argument, is called a callback function.

let's see an example:

We have here a function that takes in two variables, and a callback function.
This another function, that will be passed to fullName(), as an argument.
Now if I run this line of code.

I will get this.

Your full name is John Red.

Why Do We Need a CallBack Function?

Say we have two functions:

when we invoke them:

we will get this result :

Just as expected.

Now, let's add some changes to our first() function. so it doesn't execute immediately, means it takes some time to execute, per example 0.5s ( 500ms ).

PS: The setTimeout() method calls a function or evaluates an expression after a specified number of milliseconds.

Now if we call our functions.

we will get this result:

This doesn't mean that JavaScript executed second() then first(), it executed first() first, just it didn't wait for a response from first(), and then immediately ran second().

So you have to take in mind that, not just by calling functions in order in JavaScript, will make them execute in order.

To fix this, we use Callbacks, to make sure that a function won't execute, until another one, has already finished execution.

Watch my tutorial about CallBack functions, for more understanding ...


You're welcome to share your ideas with us in comments.


Contact Form