Global Execution Context in JavaScript

Global Execution Context

1. When we give JS code to the browser, the JS Engine will allocate (create) a global memory block for the execution of JavaScript code, called the Global Execution Context.

2. Here, we have a window variable that has a reference to the Global Execution Context.

Window Variable

1. Window variable or window object → Everything is an object in JavaScript.

2. Window is a global variable that stores the reference of the Global Execution Context.

3. The Window object is also known as the Global Object because it is available anywhere in the program.

4. The Window object has pre-defined state and behavior.

5. Variables declared with var always go to the global scope and can be accessed by the window object.

6. Any variable created in the global scope will be added to the Window object implicitly by the JS Engine.

JavaScript Code Runs in Two Phases

1. Variable Phase

2. Execution Phase

Variable Phase

1. In the variable phase, the JS Engine will check the complete JS code and search for variable declaration statements.

2. If a variable is declared, the JS Engine allocates (provides) memory for it.

3. Variables declared with var will be initialized by storing "undefined" at the time of memory block creation.
Variables declared with let and const will remain uninitialized (empty) at the time of memory block creation.

Execution Phase

1. In the execution phase, the JS Engine will execute the instructions line-by-line.