JavaScript closures and callback

Closures and callback

function iAmClosureCallBack() { var x = 100; var y = 200; setTimeout(function(){console.log('get x value '+x)}, 3000); } iAmClosureCallBack()
// after 3 seconds
get x value 100

As you can see function iAmClosureCallBack is finished calling but it's memory space is still alive with all it's variable for inner function which is setTimeout. and after 3 seconds it's invoking. While it's invoking it's looking for outer refrence for the variable x and it's getting the value due to closures which is 100.

Ok, what is callback ? how it works ?

I call function A() and supply another function to it (say function B()); my expectation function B() should be called by function A() when function A() is finished.
Cinque Terre
function iAmCaller(callmeback) { var x = 100; var y = 200; callmeback(); } iAmCaller(function(){ console.log("Im callback ");});
Im callback

iAmCaller is a function which takes another function as argument. And what we do ? we just simply pass a function while invoking iAmCaller asan argument. In this case the function is an anonymus function which just throws Im callbacl into the console. Simple enough right ! Note the name we are using here callmeback, basically it could be any random name.

callback almost in all the places 

In javascript call back mechanism is almost in everywhere. If you are aware of jquery and whatever event we perform say button click that is nothing 

but call back.

$("button").click(function(){ alert ("hello world"); }); // you can see function click event itself // is a function which takes another anonymus function // as input which will simply pop up aalert
Back Next