Synchronous VS Asynchronous

JavaScript is a single-threaded programming language which means only one thing can happen at a time. That is, the JavaScript engine can only process one statement at a time in a single thread.

First you will understand about synchronous & Asynchronous Programming.

What Is Synchronous Programming?

Synchronous Programing means tasks are performed line by line and only when one is completed, the following is unblocked. In other words, you need to wait for a task to finish to move to the next one.

console.log("First")
console.log("Second")
console.log("Third")
First
Second
Third

What Is Asynchronous Programming?

Asynchronous programing means you can move to another task before the previous one finishes. This way, with asynchronous programming you’re able to deal with multiple requests simultaneously, thus completing more tasks in a much shorter period of time.

console.log("First") 
setTimeout(() => {
        console.log("Second");
    }, 1000);
console.log("Third")
First
Third
Second

So, what the code does is first it logs in “First” then rather than executing the setTimeout function it logs in “Third” and then it runs the setTimeout function.

In the above code “First” statement got logged in. As we use browsers to run JavaScript, there are the web APIs that handle these things for users. So, what JavaScript does is, it passes the setTimeout function in such web API and then we keep on running our code as usual. So it does not block the rest of the code from executing and after all the code its execution, it gets pushed to the call stack and then finally gets executed. This is what happens in asynchronous JavaScript.

Consider another Example:

console.log('One');
setTimeout(() => {
  console.log('Two');
}, 0);
new Promise((resolve, reject) => {
    resolve('Three(promise)');
  }).then(res => console.log(res))
    .catch(err => console.log(err));
console.log('Four');
One
Four
Three(promise)
Two

Synchronous VS Asynchronous
  1. JavaScript is a single-threaded programming language.
  2. Synchronous Programing means tasks are performed line by line
  3. Asynchronous programing means you can move to another task before the previous one finishes.