Synchronous JavaScript executes code sequentially, blocking the other program until each operation completes. As a result, it can lead to slower performance. Asynchronous JavaScript, on the other hand, allows tasks to run concurrently, enhancing responsiveness by enabling non-blocking operations.
Whenever you see all these codes:
setTimeout
setInterval
Promises
Fetch
Axios
XMLHttpRequest
Remember the code is written in async js.
Main Motive of Async Js:
The primary goal of asynchronous JavaScript, or async JS, is to increase program responsiveness and efficiency, especially in situations when activities require a lot of time to finish, such as file I/O, network queries, or other potentially delayed processes. Asynchronous programming prevents blocking and improves application speed by enabling the execution of numerous tasks at once without waiting for each one to complete before going on to the next. Usually, callbacks, promises, or the async/await syntax seen in contemporary JavaScript are used to do this.
But?
Js is not asynchronous it is single-threaded but it supports async through “promises’, ”callback” and “async await” functions.
How does it work in JS?
So, here imagine we have two stacks Main stack and Side stack all the functions that have to run simultaneously, in a sequence that is synchronous code is automatically put in the main stack and async code is put onto the side stack.
The main stack also refers to execution & Side stack refers to the holding part.
Here side stack is for async code where you have to hold until the Main stack gets empty and then run the code respective to it. In easy words, whenever the main stack gets empty it checks to the side stack that there is any answer/result that would run then only it moves to the main stack shown in the figure it self.
The transfer of Data from the SIde stack to the Main stack is known as an “event loop”.
The major use cases of it are as follows:
User Interface (UI) Updates: Asynchronous operations are useful when updating the UI dynamically without causing delays in other parts of the application.
Concurrency and Parallelism: Asynchronous operations are essential for parallel execution of tasks, improving the overall performance of the application.
Timers and Intervals: Asynchronous JavaScript is used in scenarios where timers or intervals are needed without blocking the main execution thread.
Fetching Data from APIs: When making HTTP requests to APIs for data, using asynchronous operations helps prevent the browser from freezing while waiting for the response.