-
Notifications
You must be signed in to change notification settings - Fork 0
Asynchronous JS: How JavaScript Works?
- Execution Context
- Event Queue
- Call Stack
Try Me to Understand How JS Works Visually
-
The JS engine reads our code line by line with help of syntax parsers and creates a execution context (Can be more than one) which is responsible for running our code and does bit of
-
The base execution context is called Global (accessible anywhere, not inside any function) Execution context which has
- Global object -
windowobject in case of browser, it will vary in node env but there is always a global object - this keyword (which points to global object in this case)
- A link to the outer environment - which will be null in case of global execution context
- You code which it needs to run
That's why even when you don't put anything in the App.js file and run it in the browser, because we are running the Javascript file the execution context is created and we can access the window object in the browser console.
- Creation and Hoisting:
- In this step the JS setup the memory for variables (declared with var) and functions. Hence when we execution code and try to access variable which is declared later it still works as variable is already present in the memory and we can also call function which is declared later in the code
- Code Execution
- Runs the code line by line
- Every outer reference in the execution context is link to its lexical env (where it was created). When we try to find a variable declared with
varinside a function, if it can't find it there it will keep looking to its outer reference until it reaches global. This is called Scope Chain.
- It keeps information about which function is currently getting executed and what to call next
- It is stack DS which keep adding functions as they gets called
- We can view
Call Stackby going intosource tab of Dev Toolsand putting breakpoint in the code
Only does one thing at any particular time or nothing
Then how we can handle things which takes time like API calls or save to Database?
- JS Engine
- Rendering Engine
- HTTP Request
and JS Engine has hooks where it can talk to these and handover things to browser which it cannot handle by itself. The Browser then does the work and after finishing notifies JS Engine that I have finished and here is the callback method you need to execute along the with results.
The JS engine then executes the callback function and finish the operation
Hence what happens inside the JS engine is synchronous while what happens inside the browser is asynchronous