Let's understand JavaScript Execution Context

ยท

2 min read

Whenever a JavaScript engine executes a script, it creates something called Global Execution Context(GEC). Even when you do not have a single line of code in a .js file and load it, you will have the Global Execution Context created.

There are two phases in Execution Context, i.e., Creation and Execution phases. **Let see this with an example:

var firstName = 'Yash';

function getName() { console.log("Hello World"); }

getName(); The creation phase:**

1) Creates a global object, i.e., window in the web browser or global in Node.js.

2) Creates a global variable called this.

3) Memory gets allocated for the variable name and the function getName().

4) The variable name gets initialized by a value called undefined. The function getName() gets placed directly into the memory

After the creation phase, the global execution context moves to the execution phase.

The execution phase:

During the execution phase, the JavaScript engine executes the code line by line. In this phase, it assigns values to variables and starts the execution of the function calls. So the value "Yash" is assigned to the variable firstName after that getName() function executes.

For every function call, the JavaScript engine creates a new Function Execution Context. The Function Execution Context is similar to the Global Execution Context, but it creates the arguments object that contains a reference to all the parameters passed into the function instead of creating the global object.

In our example, we do not pass any arguments. Hence the length is 0.

It uses a data structure called call stack to keep track of all the execution contexts, i.e., the Global Execution Context and Function Execution Contexts.

ย