Could someone explain, why do we use callback in JavaScript? I found examples, but they could be implemented by using the normal functions. What is the advantage of using it
Because the javascript being executed is Asynchronous, therefore if you just put any old function after making the asynchronous request, it will likely be called before the original request completes. The original request will return as soon as it BEGINS (is sent out), not completes.
If you need to do something with the result of the asynchronous request, or chain together requests, etc you will need a callback to ensure the next step doesn't begin before the previous step is finished.
A callback function is executed after the current effect is finished. A more detailed example available here.
Why use callback in JavaScript, what are its advantages ?
Callback functions are basically functions (either named or anonymous) that are passed into a call on another function as an argument. The JavaScript syntax allows us to treat functions as objects so we can pass a function name as an argument of another function no problem. But we can also pass the full code of an anonymous function as an argument too, e.g. in a XMLHttpRequest response handler for a form field validation process:
req.onreadystatechange = function()
{
if (req.readyState === 4 && req.status === 200)
{
if (req.responseText !== 'Valid') // Check for invalid field value ...
{
document.getElementById(field + 'err').value = req.responseText; // ... and output detail to error field
document.getElementById(field + 'err').style.color = 'red'; // Field comment in red
document.getElementById(field + '-errchk').innerHTML = '\u00D7'; // Cross mark opposite data field
document.getElementById(field + '-errchk').style.color = 'red'; // ... in red
document.getElementById(field + '-errchk').style.fontWeight = 800; // ... and bold
}
else
{
document.getElementById(field + 'err').value = ''; // Clear error info field
document.getElementById(field + 'err').style.color = 'green'; // Field comment in green
document.getElementById(field + '-errchk').innerHTML = '\u2713'; // Check mark opposite data field
document.getElementById(field + '-errchk').style.color = 'green'; // ... in green
document.getElementById(field + '-errchk').style.fontWeight = 800; // ... and bold
}
}
}
In JavaScript the advantage of using a callback function over using a non-callback function (i.e. a function called within another function which does not include it as a parameter) lies in the callback function's range of accessible data, its scope.
Non-callback functions have access to just their own internal scope plus their own global scope plus the parameter values input to them. Beyond this they do not have any unilateral access to the scope of any code block using them. So if we want to have a non-callback function "see" certain vars/consts/functions/collections within the code that calls it, we need to move the declarations of these within the scope of the non-callback function. This is always a bit cumbersome and sometimes very tricky. Otherwise we may need to redefine the non-callback function so that otherwise non-shareable data from the calling code's scope is passed as parameters to it. This of course changes the declaration of the non-callback function and impacts any other code block that uses it.
Callback functions have access to both their own scope plus the scope of the code that calls them plus the global scope of the calling code. So callback functions are handier to manage codewise, especially in larger JS applications where data is passed across several module boundaries during execution of a task.
Callback functions existed in JavaScript from almost the beginning. At the front end of web applications, you'll see them used in things like event listeners, for example if we want to remove the mouse's on-hover text displayed when we hover away from the "Next Month" arrow of a web page calendar :
var mouseOut = function(e)
{
if (document.getElementById("right-info").innerHTML != "")
{
document.getElementById("right-info").innerHTML = "";
}
};
nextM.addEventListener('mouseout', mouseOut, false);
At the back end, callbacks were used for asynchronous data transfer between browser and server. They were also used as the original means of ensuring back-end JS scripts that included asynchronous functions (e.g. database queries, network calls, file-system actions, data loading from external devices, etc) would execute in the desired order. Basically, by including a callback function that does the operation needing to be done immediately after the async process as a parameter to the async function, we could ensure its correct sequencing w.r.t. the async process. The scoping privileges of a callback function helped the coding a bit too.
Nowadays use of callback functions at the back end is seldom used as modern JavaScript includes a Promise object that encapsulates handling of asynchronous processes in a clearer and more scalable way.
But it's still good to know what they are and where they can be effectively used.
The main browser process is a single threaded event loop. If you execute a long-running operation within a single-threaded event loop, the process "blocks". This is bad because the process stops processing other events while waiting for your operation to complete. 'alert' is one of the few blocking browser methods: if you call alert('test'), you can no longer click links, perform ajax queries, or interact with the browser UI.
In order to prevent blocking on long-running operations, the XMLHttpRequest provides an asynchronous interface. You pass it a callback to run after the operation is complete, and while it is processing it cedes control back to the main event loop instead of blocking.
There's no reason to use a callback unless you want to bind something to an event handler, or your operation is potentially blocking and therefore requires an asynchronous programming interface.
This is an excellent video discussing more about the event loop used in the browser, as well as on the server side in node.js.
EDIT: that convoluted line from the jQuery documentation just means that the callback executes asynchronously as control is ceded back to the main event loop.
parent_function(function () { console.log('Callback'); });
parent_doesnt_block(); // <-- function appears after "parent"
therefore_execution_continues();
// Maybe we get 'Callback' in the console here? or maybe later...
execution_still_continues();
Not quite like multithreading...
You use a callback anytime you need to wait on something external to your primary JS code. In a browser this is used a ton for AJAX, and in node.js it's used for every single thing that calls out to the system (file access, networks access, database requests, etc).
Let's say you want to fire an ajax request everytime a user clicks a button. Now lets say that ajax request takes 10 seconds to complete. The user then clicks 10 of these buttons before those 10 seconds are up. This would repeatedly call a function like this:
var clicked = function() {
doAjax('/some/path.json', function(result) {
updatePageWith(result.widgets);
});
};
This runs code in the JS engine for only long enough to make the request. Then it idles while it waits. Other JS can run at this point, the UI is totally fluid and interactive, everything is awesome. Then suddenly, all 10 of those requests resolve at once. And then our callback is invoked 10 times like magic.
This works because every time we call clicked()
we are creating a new function object, and passing it to the doAjax()
function. So there are 10 unique callback function objects hanging out in memory, each one bound to a specific request by the doAjax()
function. When a request returns, it finds the associated callback object and calls it.
The huge advantage here is that, although javascript is single threaded, you never tie up that thread with waiting. If you JS thread is busy, it should only ever be because it's actively running code. So even though JS is single threaded, it's trivial for your code to implicitly hold the state of any number of any kind of asynchronous tasks.
The synchronous method of callbacks are used for a different purpose usually. Like listeners or delegates. Like telling object A to callback when it's data changes. While not strictly asynchronous, you usually aren't calling that callback immediately. Instead it will be called later in response to some sort of user action of event.
Is asynchronous programming akin to multi-threading?
Yes.
Javascript's asynch model provides a way to do work "in the background".
Suppose you have a long-running calculation. This might be hard to imagine for a simple js demo, but imagine a long decompression routine, or a long-running pathfinding algorithm in a game, etc. some numerical calculation that takes more than a second.
Doing the calculation by directly invoking the function will work, but it will suspend the browser UI for the duration of the calculation. Running things asynchronously means the browser UI remains responsive, as the calculation continues running on a background thread. When the calc completes, according to the asynch programming pattern, the function invokes the callback function, notifying the application layer that the calculation is complete.