Implementing a callback with anonymous function



Callback functions

Callback functions are used everywhere.

In traditional programming languages, a callback is achieved by passing a pointer to a function to another process so that when that process completes function is called to advise the caller of a status of some sort.

In JavaScript, functions are considered objects. This means that a variable can be assigned a function, or a function can be passed into another function as a parameter.

Functions used in this way are called anonymous functions.

Anonymous function

A function is considered anonymous when it doesn’t have a name. The anonymous function declaration must begin with the function keyword, which must be followed by closed parentheses.

The parentheses can include zero or more parameters. The syntax for an anonymous function is as follows:

<script type="text/javascript">
         function (n,n,…,n) { body };
</script>

Callback with anonymous function

Callbacks are functions that are processed when the transfer of control returns to the caller.

Callback functions can also be used in the form of a parameter to another function.

The following example demonstrates a callback with anonymous function:

<body>
    <h4>If - Else evaluation - type in a number </h4>
    <h5>if<10 success - else fail</h5>
    <input type="text" id="inputValue" />
    <input type="button" value="Check" id="Button1" />
<script src="https://code.jquery.com/jquery-2.2.3.min.js" </script>
<script type="text/javascript">
    $("document").ready(function () {
        $("#Button1").click(function () {
            DoLongTask($("#inputValue").val(),
                function (result, data) {
                    if (result == "SUCCESS")
                        alert(data + " is a Success");
                    else
                        alert(data + " is a fail");
            });
        });
    
    });
    function DoLongTask(n, f) {
        if (n < 10)
            f("SUCCESS", n);
        else
            f("FAIL", n);
    }
</script>
</body>

Ads Right