Most of the time we host our code on browser/server having node.js. To understand how javascript works, let’s take an example of browser.
Let’s assume our code is hosted on a browser(chrome). This is how Javascript runs on your browser
- Every host/browser is having a parser, which checks the syntax of our code. If there is any syntax mistake in our code, the parser throws back the exception to the user.
- If the syntax is correct, the second step for the parser is to produce a data structure known as Abstract Syntax Tree. This data structure is then converted into machine code
- Once the Javascript code is converted to machine code, it then is processed by by processor and runs on our browser
The below diagram will make you understand the concept in more better way
Execution Context
Let’s have a look at the order in which our code runs.
All Javascript code requires an environment for run, consider a box/container. These are called execution context.
However, the default execution context is the global context. All the code, that is not under any function, falls under the global context.
But what about the code that is under a function ? As soon as you call a function, it gets its brand new execution context. Let’s understand this with help of an example.
On line no 124 we are in Global Execution Context. As we move to line no 141 we are still here in Global execution context where function first is being called. As we move inside the function, a new execution context is assigned to function first, then second and then third.
As the execution of function third, second and first gets completed, the execution context of respective function keeps on getting removed. In the end Global Execution Context is left for further execution if any.
Execution Context in Detail
The execution context consists of 3 parts.
- Variable Object: This contains function arguments, inner variable declaration as well as function declaration
- Scope Chain: This contains the current variable objects as well as variable objects of all its parents
- This variable: This points to the current object
Whenever a new execution content comes into picture, it consists of 2 phases:
Creation Phase
- Creation of variable object
- Creation of scope chain
- Determine value of “this” variable
Execution Phase
- The code of the function that generated the current execution context is ran line by line
The Variable Object
- In variable object, the argument object is created, containing all the arguments that were passed into the function
- Code is scanned for function declaration: for each function, a property is created in the variable object, pointing to the function
- Code is scanned for the variable declaration: for each variable, a property is created in the variable object, and set to undefined