All VideosJavaScript Tutorials

Synchronous and asynchronous in JavaScript JavaScript Tutorials in Hindi Interview Question #42

In JavaScript, synchronous and asynchronous refer to different ways in which code is executed and how tasks are handled.

Synchronous Code Execution:

  • Synchronous code executes sequentially, one line at a time, in the order it appears.
  • Each line of code waits for the previous one to finish executing before moving on to the next line.
  • Execution of the code blocks further code execution until it’s finished.
  • This can sometimes lead to blocking behavior, especially when dealing with I/O operations or long-running tasks.

Example of synchronous code:

console.log("One");
console.log("Two");
console.log("Three");
console.log("Four");

In the above code, “Start” is logged, then “Middle”, and finally “End”. Each statement is executed in sequence.

Asynchronous Code Execution:

  • Asynchronous code does not wait for tasks to finish and does not block further code execution.
  • It allows multiple tasks to be executed concurrently, improving performance and responsiveness.
  • Callbacks, Promises, and async/await are commonly used mechanisms for handling asynchronous operations in JavaScript.

Example of asynchronous code using callbacks:

console.log("Start");

setTimeout(function() {
    console.log("Middle");
}, 2000);

console.log("End");

In this example, “Start” is logged first, then “End”. The setTimeout function schedules the execution of its callback function after 2000 milliseconds, but it doesn’t block the execution of subsequent code. So, “End” is logged immediately after “Start”, while “Middle” is logged after a delay of 2000 milliseconds.

Asynchronous code is crucial for handling operations like fetching data from a server, reading files, or handling user input without blocking the main execution thread. It allows JavaScript to be more responsive and efficient in handling tasks.

Leave a Reply

Your email address will not be published. Required fields are marked *

error: Content is protected !!