1

I am trying to understand callback functions in javascript.

There is a function something like

function load() {

 var func = function(data){
  ///

 };
}

Can anyone explain me from where the parameter "data" will be returned, as I dont see any variable declared in the file.

1 Answer 1

3

In JavaScript, functions are first class objects. You could store them in objects (variables) and pass them around as arguments to functions. Every function is actually a Function object.

You don't have a callback function in that example. You'd have one when you pass a function as an argument to another function.

This is a function that invokes a callback function when it is ready:

function load (ready_callback) {
   // do some stuff

   ready_callback();
}

Which can be invoked as follows:

function callback () {
   alert('Ready');
}

load(callback);

Or:

var callback = function () {
   alert('Ready');
}

load(callback);

Or:

load(function () {
   alert('Ready');
});

The above three example are pretty much equivalent.

Callback functions are typically used for event handling and asynchronous methods. One example is the setTimeout() method, which invokes a callback function when a timeout expires:

var timerCallback = function () {
   alert('Timeout Expired!');
}

setTimeout(timerCallback, 5000);  // Set the timeout to 5 seconds
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.