Synchronous vs Asynchronous
Synchronous execution is plain and straightforward. Let’s say you have three lines of code, Lines 1, 2, and 3. Line 2 gets executed only after Line 1 has finished execution. Line 3 after Line 2, and so on.
1console.log("Hi"); // line 1
2console.log("I am"); // line 2
3console.log("John"); // line 3
Async (which literally means "out of sync") happens differently. Let us take the same example of having three lines of code, but Line 2 takes more time to execute. In the asynchronous case, do Lines 1 and 3 wait for it to complete? No, they don’t. Lines 1 and 3 finish execution and the result of Line 2 is returned later, when available.
This can be easily exhibited using the setTimeout()
method in JavaScript. This is often used to demonstrate synchronous and asynchronous code execution. Don’t worry if you don’t understand the syntax, we will explain it step by step.
Lines 1 and 3 have a simple console.log()
statement. The setTimeout()
function takes a callback as an argument and the next parameter that you see is the delay in milliseconds. Once the delay is completed, the callback (which is a function) is executed.

xxxxxxxxxx
console.log("Hi");
setTimeout(() => {
console.log("I am");
}, 2000)
console.log("John");