𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁 𝗦𝘆𝗻𝗰𝗵𝗿𝗼𝗻𝗼𝘂𝘀 𝗮𝗻𝗱 𝗔𝘀𝘆𝗻𝗰𝗵𝗿𝗼𝗻𝗼𝘂𝘀
JavaScript runs on a single thread. This means it executes one thing at a time. You need to understand how it handles tasks to write efficient code.
Synchronous JavaScript
Synchronous code runs line by line. Each task waits for the previous task to finish. This is called blocking. If one task takes a long time, the whole program stops.
- Execution: Fixed sequence.
- Blocking: Yes.
- Complexity: Simple.
- Best for: Simple, sequential tasks.
Asynchronous JavaScript
Asynchronous code runs independently. Tasks do not block other code while they wait. This is called non-blocking. The task starts in the background and notifies you when it finishes.
- Execution: Tasks run independently.
- Blocking: No.
- Complexity: Higher.
- Best for: API calls, timers, and file operations.
Three ways to handle asynchronous tasks:
- Callbacks: A function that runs after a task finishes.
- Promises: An object that represents the completion or failure of an operation.
- Async/Await: The cleanest method. It makes asynchronous code look like synchronous code without blocking the thread.
Common asynchronous operations:
- Timers: setTimeout()
- API calls: fetch()
- File reading: readFile()
- User events: addEventListener()
The Event Loop makes this work. It uses the Call Stack, Web APIs, and a Callback Queue to manage multiple tasks at once.
Summary:
- Synchronous: One after another. Blocks execution.
- Asynchronous: Independent tasks. Does not block.
- JavaScript default: Synchronous.
Source: https://www.geeksforgeeks.org/javascript/synchronous-and-asynchronous-in-javascript/ Source: https://www.w3schools.com/js/js_asynchronous.asp Source: https://medium.com/@mohdtalib.dev/what-is-synchronous-and-asynchronous-in-javascript-07adb7b4cc5f
Full post: https://dev.to/raja_b_0c9d242e2c26cf063b/javascript-synchronous-and-asynchronous-2a69