Learn Synchronous and Asynchronous JavaScript
Source: Dev.to
Synchronous
In synchronous programming, tasks are executed one after another in order. Each line of code waits for the previous one to finish before moving to the next, resulting in a clear and predictable flow.
console.log("Start");
console.log("Task 1");
console.log("Task 2");
console.log("End");Output
Start
Task 1
Task 2
EndEach statement runs only after the preceding one has completed, so the code executes in a fixed, step‑by‑step order.
Asynchronous
In asynchronous programming, tasks can run independently without waiting for previous tasks to finish. While one task is in progress, other code can continue executing, improving performance and responsiveness.
console.log("Start");
setTimeout(function() {
console.log("Task 1");
}, 2000);
console.log("End");Output
Start
End
Task 1setTimeout runs asynchronously, so the interpreter does not wait for the timer to finish before moving on to the next line.
How Asynchronous JavaScript Works
Call Stack
The call stack is where JavaScript executes functions. It processes code in a last‑in, first‑out (LIFO) manner.
Web APIs (Browser)
Browser‑provided Web APIs handle tasks such as setTimeout, network requests, and event listeners. When you invoke one of these APIs, the request is handed off to the browser, allowing the JavaScript engine to continue running other code.
Callback Queue
Once a Web API completes its work (e.g., the timer expires), it places the associated callback function into the callback queue.
Event Loop
The event loop continuously checks the call stack. If the stack is empty, it moves functions from the callback queue onto the call stack for execution. This mechanism ensures that delayed or asynchronous tasks run only after the main synchronous code has finished.