𝗨𝗻𝗱𝗲𝗿𝘀𝘁𝗮𝗻𝗱𝗶𝗻𝗴 𝗦𝘆𝗻𝗰𝗵𝗿𝗼𝗻𝗼𝘂𝘀 𝗮𝗻𝗱 𝗔𝘀𝘆𝗻𝗰𝗵𝗿𝗼𝗻𝗼𝘂𝘀 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁
JavaScript runs one task at a time. This is because it is a single-threaded language.
To build fast apps, you must know the difference between synchronous and asynchronous code.
Synchronous Execution
Code runs line by line. Each task waits for the previous one to finish.
Think of an ATM line. Person two cannot use the machine until person one finishes.
If one task takes a long time, the whole program stops. This is called blocking.
Asynchronous Execution
Tasks run independently. JavaScript starts a task and moves to the next one immediately.
Think of a restaurant. You order food, then you talk to friends while you wait. You do not sit still and wait for the food to arrive before doing anything else.
Asynchronous code prevents your application from freezing during:
- API requests
- Database queries
- File reading
- Image uploads
Three ways to handle asynchronous code:
Callbacks A function runs after a specific task completes. It is like a delivery driver calling you when your food arrives.
Promises A promise represents a future result. It stays in a pending state until it is either resolved (success) or rejected (error).
Async/Await This makes asynchronous code look like synchronous code. It is easy to read. You use await to pause a function without blocking the rest of your program.
How it works under the hood:
JavaScript uses an Event Loop to manage these tasks.
- Call Stack: Tracks your current functions.
- Web APIs: Handles long tasks like timers or fetches.
- Callback Queue: Holds completed tasks.
- Event Loop: Moves tasks from the queue to the stack when the stack is empty.
Comparison:
Synchronous:
- Runs sequentially
- Blocks the program
- Simple to write
- Slow for heavy tasks
Asynchronous:
- Runs independently
- Non-blocking
- More complex
- Efficient for web apps
Mastering these concepts is the key to using React, Node.js, and modern APIs.
Source: https://www.geeksforgeeks.org/javascript/synchronous-and-asynchronous-in-javascript/ Source: https://www.browserstack.com/guide/synchronous-vs-asynchronous-in-javascript Full post: https://dev.to/annapoo/understanding-synchronous-and-asynchronous-javascript-5gea