Javascript is too slow! But wait

How async nature, event loop & promises makes it fast

😅 Being a single threaded language most of the people think that Javascript or NodeJS is slow and not scalable. Python and JS be like:-

Well, it depends. If your service is I/O (input output like file reading, DB call, Http call etc) heavy which means it has dependency on other resource being read or written.

⚡️ There, NodeJS performs good as compared to other stacks in general when your service is IO heavy instead of CPU heavy.

❓ This is because NodeJS or JS has something like handing over its work to the underlying thread of the Operating system to carry out IO execution.

It passes the callback (a function) to that thread and continue with the execution of other instructions in the code, which is called async programming also in fancy terms.

Well Well Well, Let's take a step back and understand what we wrote above:-

## Blocking nature of JS

- Javascript is a single threaded language and hence can work on one task at a time unlike Java where multiple threads are present to handle workload in parallel (multithreading).

- So, if one function/instruction is running, next instruction will wait for this instruction to get completed and we can't run them in parallel.

Let's see how one instruction blocks another one:-

✅ You can refer video explanation (in english) with code examples and v8-engine internals here:- https://www.youtube.com/watch?v=JN89L2SqPA8

## Non blocking nature

Now, in JS runtime environment (NodeJS) we have some C++ APIs that have some functions like setTimeout, Promises, localStorage which are executed by the threads of our Operating systems, not by the main JS thread.

You can see the right box having C++ APIs here:-

- Whenever, we perform IO through any C++ API like executing a promise , performing HTTP call or DB operation etc JS main thread hands over the main work to the OS thread and the main thread of JS continues working on other code and doesn't wait for the Async code to run.

- It provides a callback (a function) to execute when call stack gets empty (call stack has only the sync code and async code goes to microtask or task queue)

- Event loop, loops through these queues when call stack gets empty & put the callbacks from these queues to the main stack and returns the result.

For more in depth details of How promises are implemented in C++ code, refer this:- https://www.youtube.com/watch?v=JN89L2SqPA8

-----------------------------------