Synchronous vs Asynchronous in JavaScript

Synchronous vs Asynchronous in JavaScript

What is Synchronous in JavaScript?

JavaScript is a synchronous single-threaded language.

Synchronous means the execution of the code happens sequentially means only one statement can be executed at a time. Each statement executes after the execution of the previous statement.

See the following code example of synchronous JavaScript

console.log('First');
console.log('Second');
console.log('Third');

// Output

First
Second
Third

In the above code, only one statement is executed at a time.

What is blocking?

In synchronous programming, the next statements get blocked due to the previous statement, which causes a delay in the user interface, this phenomenon is known as Blocking.

What is Asynchronous in JavaScript?

Asynchronous means the execution of the code happens in parallel means more than one statement can be executed at a time, which means the current statement gets executed in the background and the next statement gets executed immediately.

See the following coding example to understand how javascript works asynchronously -

console.log('First');

// Set timeout for 2 seconds
setTimeout(() => console.log('Second'), 2000);

console.log('Third');

//Output

First
Third
Second

Output -

As we can see in the output of the above code example, the Third gets printed before the Second, because of the asynchronous execution of the code. Here setTimeout() function waits for 2 seconds, and in the meantime, the next statement gets executed without waiting for the previous one to complete the execution.

setTimeout() is an asynchronous method.

What is the Difference Between Synchronous vs Asynchronous JavaScript?

Sr. no.Synchronous JavaScriptAsynchronous JavaScript
1Execution happens in sequence.Execution happens in parallel.
2Only one statement gets executed at a time.More than one statement can be executed at a time.
3Each operation waits for the previous operation to complete its execution.The next operation can be executed while the previous operation gets executed in the background.

Final Words

And that’s it for this blog.

I hope you’ve found this blog a good referencing resource and thank you for reading.

If this blog was helpful, please do like, comment and share. Thanks, see you in the next blog.✌️