What Actually Synchronous And Asynchronous Code In JavaScript

In this tutorial i am going to discuss about asynchronous JavaScript. If you are a JavaScript developer then you will often face asynchronous JavaScript behavior. In real life which can be confusing for programmers who only have experience with synchronous code with JavaScript. 

Have you ever faced that situation? In this asynchronous javascript example tutorial i will clear your concept about asynchronous and synchronous javascript code and what actually they are. 

Synchronous Code in JavaScript

In synchronous piece code, if you have two lines of programs (L1 followed by L2), then L2 cannot begin running until L1 has finished executing. Suppose you are standing a rail station and you want to buy a ticket. but can not buy a ticket until the people ahead of you completed their buying of ticket. And also same for people behind you, they can not buy ticket until your buying is completed. hope you have got the point from this example.

Asynchronous Code in JavaScript

In asynchronous code, you can have two lines of programs (L1 followed by L2), where L1 schedules some task to be run in the future, but L2 runs before that task completes.

Let's see an exmaple. Imagine as if you are eating at a cafe. Other peoples order their food. You can also order your food. You don't have to wait for them to receive their food and finish eating before you order.

Example of asynchronous code:

// Say "Hello."
// Say "Goodbye" two seconds from now.
setTimeout(function() {
}, 2000);
// Say "Hello again!"
console.log("Hello again!");


If you are only familiar with synchronous code, you may expect the code above to behave in the following way:


Say "Hello".
Do nothing for two seconds.
Say "Goodbye!"
Say "Hello again!"


But setTimeout does not pause the execution of the code. It only schedules something to happen in the future, and then immediately continues to the next line.


Actual Output
Say "Hello."
Say "Hello again!"
Do nothing for two seconds.
Say "Goodbye!"


Hope you have understand that what is synchronous and asynchronous code in JavaScript and how they executed. Hope it can help you.