Skip to content

Asynchronous JS: How JavaScript Works?

Preeti Wadhwani edited this page Jun 12, 2021 · 10 revisions

JS Engine consists of

  • Execution Context
  • Event Queue
  • Call Stack

JS Engine Inside the Browser

Try Me to Understand How JS Works Visually

Execution Context

  • 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

  1. Global object - window object in case of browser, it will vary in node env but there is always a global object
  2. this keyword (which points to global object in this case)
  3. A link to the outer environment - which will be null in case of global execution context
  4. 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.

To Create Execution Context JS does two steps

  1. 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
  1. Code Execution
  • Runs the code line by line

Scope Chain

  • 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 var inside 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.

Call Stack

  • 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 Stack by going into source tab of Dev Tools and putting breakpoint in the code

JavaScript is a Single Threaded Language

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?

The Browser consist of:

  • 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

Clone this wiki locally