Synchronous & Asynchronous || Javascript

Synchronous

  1. Synchronous: In synchronous programming, tasks are executed one after the other in a sequential manner. Each task must wait for the previous one to complete before it can start. When a synchronous function is called, the program execution is blocked, and it waits until that function completes before moving on to the next line of code. If any task takes a long time to execute, it can cause the entire program to stall and become unresponsive.

Example: -

function syncTask() {

console.log("Start Synchronous Task");

// Simulating a time-consuming synchronous task

for (let i = 0; i < 5; i++) {

console.log("Processing step " + I);

}

console.log("End Synchronous Task");

}

console.log("Before calling synchronous task");

syncTask();

console.log("After calling synchronous task");

Asynchronous

Asynchronous: In asynchronous programming, tasks are executed independently of each other. When an asynchronous function is called, it doesn't block the program execution. Instead, it initiates the task and moves on to the next line of code immediately without waiting for the task to complete. The result of the asynchronous task is usually handled through callbacks, promises, or async/await, allowing the program to continue processing other tasks while waiting for the asynchronous operation to finish. This helps in better performance and responsiveness, especially in tasks involving I/O operations, network requests, or waiting for user input.

Example: -

function asyncTask() {

console.log("Start Asynchronous Task");

// Simulating a time-consuming asynchronous task

setTimeout(() => {

console.log("Asynchronous Task Completed");

}, 2000); }

console.log("Before calling asynchronous task");

asyncTask();

console.log("After calling asynchronous task");

Javascript:-

JavaScript supports both synchronous and asynchronous operations. In the early days of JavaScript, it was mainly used for synchronous tasks, running in the browser environment. However, with the introduction of newer features like Promises and async/await, JavaScript became more capable of handling asynchronous operations effectively. Today, JavaScript is widely used in both synchronous and asynchronous contexts, such as handling events, making HTTP requests, reading/writing files, and more.