JS, how do you work ?

JS, how do you work ?

  • A javascript file is not directly understood by the browser

  • A Js engine, which is present in every browser acts as a translator & converts this javascript file into machine readable language(binary inputs of 1s & 0s)

Screenshot 2021-06-20 at 12.46.08 AM.png

  • This js engine is also written in some language(eg, V8 engine present in chrome is written in c++)

Let us understand more about this Javascript Engine A Js engine has a memory stack, call stack

  1. Memory heap, responsible for storing variables etc

A very simple explanation is that the heap is the portion of memory where dynamically allocated memory resides (i.e. memory allocated via malloc). Memory allocated from the heap will remain allocated until one of the following occurs:

The memory is free'd The program terminates

2.Call stack, responsible for executing functions Stack memory which is where local functions live. Memory allocated on the stack generally only lives until the function returns

Screenshot 2021-06-19 at 2.34.04 PM.png

  • As we have only 1 call stack, we can execute only 1 task at a time, hence javascript is called Single Threaded

  • We just cannot have multiple call stacks for making js multi threaded. It may cause complexities by creating deadlocks etc.

  • So to execute multiple tasks at the same time there is Asynchronous javascript been introduced

  • Inorder to execute asynchronous js code , it is not just the js engine which is in picture, there is complete javascript run environment which is responsible. Lets take below example into consideration

carbon.png

Screenshot 2021-06-20 at 12.25.15 AM.png

console.log("Mumbai") will be pushed into callstack which gets printed

Then setTimeout is seen, which is a browser api ,then callStack realizes that it cannot execute it, so it pushes it onto the Browser Api stack, hence pushed there. It will be executed after 3 seconds.

Screenshot 2021-06-20 at 12.26.39 AM.png

Screenshot 2021-06-20 at 12.23.59 AM.png

Meanwhile, there is console.log("Goa") seen. So it is pushed into callstack for execution & it gets printed

Meanwhile, when 3 seconds are over, console.log("Pune") gets printed

Screenshot 2021-06-20 at 12.23.24 AM.png

All this being handled by Event Loop, which constantly keeps checking if call stack is empty or not & if there is something in callback queue to be executed. If there is something in the queue, it is then pushed into the stack to be executed

This is how javascript is executed