Callback Functions in JavaScript

Posted by & filed under Ajax, JAVASCRIPT, JQUERY.

Callback functions are incredibly useful not only in JavaScript, but also in a plethora of other programming languages like C, Python, etc. In this article, I will cover all the essential points to throw some light on the way the callback functions work and the way they are implemented.

Callback Functions in JavaScript

A callback function is a function in which a reference to a chunk of executable code is passed as an argument to another code.

Let’s explain it with a piece of simple JQuery example.

Example 1:

$('.class').example('arg1', function() {
    // callback function example
});

In the above JQuery example, example() method is called. It has two arguments – the first argument (arg1) gives a certain value and the second argument is an optional callback function (function()). Here the function() will be executed, once the example method will be completed.

Using a Callback Function

gCallback Functions in JavaScript

You may keep the callback function optional or mandatory. Let’s understand both the approaches with an example.

Example 2: Mandatory callback function

function myResult(p1, callback) {
    alert('I passed the exam.\n\nI scored: ' + p1);
    callback();
}

myResult('96', function() {
    alert('I got 1st division.');
});

In example2, myResult is a function that accepts two parameters. The second parameter is the callback function. When this function executes, it returns an alert message with the passed value and it then executes the callback function and outputs another alert message.

Example 3: Optional callback function

function myResult(p1, callback) {
    alert('I passed the exam.\n\nI scored: ' + p1);
    if (callback) {
        callback();
    }
}

myResult('96');

In the example3, I have represented a case when no function is passed to callback. This is an optional callback. It occurs when no callback function is passed to a function. Here, the myResult function first returns an alert message with the value for the first parameter, and then checks if there is any function passed to its callback parameter; since only one argument is passed, there will be only one alert message.

Example 4: To check whether the passed argument for the callback is a function or not

function myResult(p1, callback) {
    alert('I passed the exam.\n\nI scored: ' + p1);
    if (callback && typeof(callback) === "function") {
        callback();
    }
}

myResult('96', 'not a function');

To make sure that the passed argument is a function, you can use the typeof operator. This operator will help you identify whether the value passed to the callback parameter is a function or not. With this approach, you can keep errors at bay.

In the above example, the function myResult will output an alert message and then check for the type of the argument that has been passed to it. It will then execute the callback() function, only if the passed value will be of function type.

When a Callback Function will execute when there is an asynchronous action

Callback Functions in JavaScript

If we place a callback function at the end of a function, it will be executed at the end. But, it is interesting to note the execution sequence when an asynchronous event is included in the function before making a call the callback function. In this kind of situations also, the callback function will execute after the asynchronous action begins, but one thing is certain that callback will definitely run before the completion of the included event.

Let’s delve deep into it with an example.

Example 5: Execution time of callback function in the presence of an animation

function myResult(p1, callback) {
   alert('I passed the exam.\n\nI scored: ' + p1);
  
    $('#result').animate({
        opacity: 0
    }, 1000, function() {
        // Animation ends.
    });
  
    if (callback && typeof(callback) === "function") {
        callback();
    }
}

myResult('96', function() {
    alert('I got 1st division.');
});

By executing this piece of code, you can observe that despite the callback function is included after invoking an animation, the callback function will be executed before the animation actually ends. You can also make it execute in a synchronous way by including the callback within the animate function.

In JavaScript, you can use callbacks to accomplish a task in an asynchronous manner. This allows one to continue with some other task while waiting for the execution of a callback function.

Callback functions are a very powerful tool that add to the credibility of the JavaScript language. I hope this simple post will help you gather better insights into the implementation of the callback functions. Though it is a quite basic post, it will help you efficiently get started with implementing callbacks in JavaScript, and create a requisite program.

Author Bio:

Juana Steves is an outstanding Java developer and blogger at Xicom Technologies – a Java Development Outsourcing Company. She loves to write about java web application and web applications. Join her on Twitter and Google+ to get the latest reviews and updates.

Download Premium Only Scripts & 80+ Demo scripts Instantly at just 1.95 USD per month + 10% discount to all Exclusive Scripts

If you want any of my script need to be customized according to your business requirement,

Please feel free to contact me [at] muni2explore[at]gmail.com

Note: But it will be charged based on your customization requirement

Get Updates, Scripts & Other Useful Resources to your Email

Join 10,000+ Happy Subscribers on feedburner. Click to Subscribe (We don't send spam)
Every Email Subsciber could have access to download 100+ demo scripts & all future scripts.

%d bloggers like this:

Get Instant Script Download Access!