Being a single threaded synchronous language how javascipt handles the async code

First of all Javascript, is a single threaded synchronous language so that means javascript have single thread to exexute all its code so it performs single task at a time not more than one task, but in many other languages they are multi threaded so they will perform multiple tasks at a time.

Synchronous means it will perform futher tasks after completing its current tasks so i mean if it is performing line number 10 it will starts to perform line number 11 only after executing line number 10

Now lets take an example line number 10 is taking 1 minute of time to complete after that javascript will picks up the line number 11 and so on.....

so waiting at line number 10 for that much time leads to the bad performance of website(becuase javascript is not doing anything on that time so users not able do anything during that phase, that leads to bad user Experience )

so somehow javascript needs to perform others things during that time, so javascript needs to handle code in asynchronous way if code is taking more time

And the Callbacks,Event Loop helps javascript to do async tasks

#Callbacks

  1. Callbacks are the functions which we pass as an argument to the other functions
  2. Callbacks are very poweful,it gives us access to the async world in a synchromous language

Lets understand by taking an example: example:let's consider we have to fetch image server and need to apply some style to that image

synchronous way of doing:

function download(url) {
    // ...
}

function process(picture) {
    // ...
}

download(url);
process(picture);

However, downloading a picture from a server takes time depending on the network speed and the size of the picture.

so waiting to complete download and applying style is not the optimal solution so we have handle in a asynchronous way using call backs

To resolve this issue, you can pass the process() function to the download() function and execute the process() function inside the download() function once the download completes, like this:

function download(url, callback) {   
        // script to download the picture here
        const image=(`Downloading ${url} ...`);

        // process the picture once it is completed
        callback(image);

}

function process(image) {
    console.log(`Processing ${image}`);
}

let url = 'https://www.getthepic.jpg';
download(url, process);

So that's how Javascript handles the code which takes some tome to complete execution

callbacks are oneside of coin to help us to do async tasks and other side is Event loop will see that in next blog.