Callback function example

When you pass a function as an argument, it is known as a callback function, and when you return a value through this callback function, the value is a parameter of the passed function.

function myFunction(val, callback){
    if(val == 1){
        callback(true);
    }else{
        callback(false);
    }
}

myFunction(0, 
//the true or false are passed from callback() 
//is getting here as bool
// the anonymous function below defines the functionality of the callback
function (bool){
    if(bool){
        alert("do stuff for when value is true");
    }else {
        //this condition is satisfied as 0 passed
        alert("do stuff for when value is false");
    }
});

Basically, callbacks() are used for asynchronous concepts. It is invoked on a particular event.

myFunction is also callback function. For example, it occurs on a click event.

document.body.addEventListener('click', myFunction);

It means, first assign the action to other function, and don’t think about this. The action will be performed when the condition is met.

Leave a Comment