What is the use of a synchronous callback function in JavaScript?

asynchronous, callback, javascript

Solution

Some very common examples of synchroneous callbacks are the methods on `Array.prototype`: `forEach`, `map`, `filter`, etc.

The role of the callback is to provide a partial implementation that can be easily swapped in a larger algorithm. Some design patterns like template method and strategy come to mind.

Problem

I have been doing extensive reading on asynchronous programming for the web and use of callbacks in JavaScript and jQuery. I have understood the fundamentals of AJAX. What I cannot figure out is the use of callback functions when not used in asynchronous programming. From my understanding, simply adding a callback to a function does not make it non-blocking/asynchronous. Asynchronous capability is actually provided by the environment (browser APIs). So adding a callback to a function that I have written will not lead to any asynchronous execution. For example: ``` var X; function Test(A, B, Callback) { X=A+B*A*B; Callback(X); } Test(99999,999999,function(Data) { alert(Data); }); alert("This is not printed first, as it would be in Async."); ``` In the above I'm taking two numbers and performing algebraic operations on them. Even though I'm using a callback function, the code execution will be blocked while the operations are performed. Then the callback will be executed, displaying an alert with the result of the computation. Then the next alert follows. Had I made an XMLHttpRequest instead of the algebraic operation, I would have got the second alert first because of asynchronous implementation. The code flow would not be blocked during the request as is happening during the mathematical operation. Thus, what is the use of a callback in non-async calls when code execution is blocked even with a callback?

Original source