Hi All,

On today’s post, I’ll be teaching you guys the Callback functions in javascript.

Basically we need call back for manage Synchronization in javascript. But why ?. Javascript is asynchronous language where it will not stop for IO operations to get completed and etc. Image you want to complete two task sequentially. What we normally do is create two functions and call them sequentially. (eg- we have two functions where first function prints “Hello World” and the other one prints “Bye World”). Our requirement is to print “Hello World” first and “Bye World” second. Lets execute the following code set and see the output.

(function printHello(){
console.log("Hello World!");
})();

(function printBye(){
console.log("Bye World!");
})();

 

And the output will be :

Hello World!

Bye World!

But what if we want to wait 10 seconds before print “Hello World!” and then only print “Bye World!” ?.

OK, lets try it same like the previous example.

setTimeout(function printHello(){
console.log("Hello World!");
},3000);

(function printBye(){
console.log("Bye World!");
})();

And the output will be :


Bye World!

Hello World!

@!#??? What ? This is not what we expected 😦

This happens because as i mentioned earlier this is a result of javascript asynchronus behavior. But by using Callbacks / Promises (A tutorial about javascript promises will be post verysoon) we can get what we want.

But how ?

What if i told u that we can pass a function to another function as a parameter. Seems legit right?. Yes we can pass a function as a parameter to another function that is what we calling callback here. Lets try it out.

function printHello(callback){
console.log("Hello World!");
callback();

};

function printBye(){
console.log("Bye world!");
};

setTimeout(printHello, 2000,(printBye));

And the output will be : 

Hello World!

Bye World!

In the above code when we calling the printHello() function through the setTimeout command we are passing printBye as a parameter where printBye is another function in our code. in printHello function there is a parameter called callback and after printing “Hello World!” the system will execute callback() line where callback = printBye so callback() = printBye(). (Note: Try passing a dummy value eg-“asd” or “xxx” or a dummy variable as a parameter to the printHello and see the output. There will be an error saying that asd is not a function. 

setTimeout(printHello, 2000,("asd"));

 

 

That is callback in javascript and that’s all for today 🙂 .

Brought to you by Yinza's Class Room.

 

 

Advertisements