JavaScript Asynchronous Programming – How Callbacks Work

asynchronous-programmingjavascript

I've been doing a lot of reading online trying to figure out how to write asynchronous JavaScript code. One of the techniques that has come up a lot in my research is to use callbacks. While I understand the process of how to write and execute a callback function, I'm confused why callbacks seem to automagically make the JavaScript execution asynchronous. So, my question is: how does adding in callback functions to my JavaScript code make said code automagically async?

Best Answer

It doesn't. Just taking a callback or passing a callback doesn't mean it's asynchronous.

For example, the .forEach function takes a callback but is synchronous.

var available = false;
[1,2,3].forEach( function(){
    available = true;
});
//code here runs after the whole .forEach has run,
//so available === true here

The setTimeout takes a callback too and is asynchronous.

function myFunction( fn ) {
    setTimeout( function() {
        fn(1,2,3);
    }, 0 );
}

var available = false;
myFunction( function() {
    available = true;
});
//available is never true here

Hooking to any asynchronous event in Javascript always requires a callback but that doesn't mean calling functions or passing them around is always asynchronous.