Thursday, 22 January 2015

Callback Functions In JavaScript

Introduction

If we can pass any executable code as an argument to any function, then that piece of code is called Callback.

If you have come from JQuery background then you have used this approach several times unknowingly.

Digging callback in JQuery

We have use below piece of code many times.Let's dissect it
$(document).ready( function(){
     console.log("I am a callback function");
});

1) Select document object.
2) Call ready function.
3) Inside ready function passing anonymous function as a parameter.

So we can write above code as;

var callback = function(){
   console.log("I am a callback function");
}
$(document).ready(callback);

So we are passing a executable piece of code as callback and that code is a function itself.

JavaScript Functions

In JavaScript functions are first-class objects.

1) Functions are objects in JavaScript.
2) Objects can be used as any other first class objects i:e they can be stored in variable , can be passed as an argument,etc.


How to create callback function

1) Put the callback as last argument.
2) Check the callback, whether it is defined or not.
3) Check  whether callback is a function or not.


No comments:

Post a Comment