JavaScript Execution Context and JS Engine Components
Tags: javascript, programming, deeplearning, tutorial
Published: 2024-05-24 13:03:36

Hello everyone! Welcome to my blog, where I’ll be documenting my journey to mastering the JavaScript language. This is the first post in what will be a series chronicling my experiences, challenges, and triumphs as I dive deep into the world of JavaScript. I hope you'll join me on this adventure, learn alongside me, and share your own insights. Enjoy the read!

## Goals and Objectives in this topic:

- Understand the concept of Execution Context. 
- Understand the following Components:
 - Clean up.
 - Call Stack.
 - Heap.
 - Built-in Functions and Objects.
 - Type Information.

### Before we start, we need to understand first on how JavaScript Engine process our simple  block of code.

To demonstrate this components in action here' a simple code for demonstration.

```
var age = 12;

console.log(age);

function logAge(ageArg) {
  console.log(`log AGE is ${ageArg}`);
}

logAge(age);
```


> When the JavaScript Engine Starts Running the Code, it creates a global Execution Context. This context is divided in to two parts Creation Phase and Execution Phase.


###**1. Global Execution Context** (**_Creation Phase_**):

**Memory Allocation**: Space is reserved in the Heap (_unstructured storage_) for the variable `age`.

**Initialization**: The variable `age `is initialized with the value `undefined `(default for var variables in JavaScript).

> In JavaScript with `var` variables, initialization with the actual value happens during the **_execution phase_** when the line with the assignment is encountered. The **_creation phase_** only allocates memory and assigns `undefined`by default.


**Reference Creation**: A reference is created in the global scope pointing to the memory location of age in the Heap. This allows you to access age using its name throughout the global scope.

**Function Definition** (**_not Creation_**): The function `logAge `is defined and stored in memory. This includes its code and argument (ageArg). However, the function itself isn't executed yet.

###**2. Global Execution Context** (**_Execution Phase_**):

**Variable Assignment**: The line `age = 12;` is encountered. The value 12 is assigned to the previously allocated memory location for age.

**Console Output**: The line `console.log(age);` is executed. The value of age (which is now 12) is retrieved from the Heap using the reference in the global scope and printed to the console.

**Function Call**: The line `logAge(age);` is reached. This triggers the creation of a separate execution context for the `logAge `function.

> **Each function call creates a new execution context** to manage the function's execution environment, including its scope, arguments, and call stack frame.

###**3.Function Execution Context** for `logAge` (**_Creation Phase_**):

**Note: This phase happens only when `logAge` is called.**

**Memory Allocation**: If `logAge `has any arguments (like ageArg in this case), memory is allocated for them in the Heap within this context.

**Local Variable Initialization** (if any): Any variables declared within the `logAge `function are initialized, usually with undefined.

###**4. Function Execution Context** for `logAge `(**_Execution Phase_**):

**Argument Passing:** The value of age (which is 12 from the global context) is passed as an argument to the `logAge `function and assigned to the `ageArg `parameter within the function's execution context.

**Function Body Execution:** The code within the `logAge function`is executed. In this case, it uses template literals to construct a string and then logs it using console.log.

#### Overall Sequence:

1. Global Execution Context (Creation Phase)
2. Global Execution Context (Execution Phase) - including variable assignment, console output, and function call
3. Function Execution Context for logAge (Creation Phase) - only when the function is called
4. Function Execution Context for logAge (Execution Phase) - function body execution

**Cleaning Up**: The JavaScript engine employs a garbage collector to manage memory. Once the function execution context for logAge is complete and there are no more references to the function arguments or local variables, the memory used by them in the Heap becomes available for garbage collection.

**Call Stack:** 
- The call stack keeps track of the currently executing function and its arguments.
- In this code, the call stack would have:
 - logAge function call when it's executed.
 - The global execution context when the script starts running.

**Heap:**
- The Heap stores the values of variables and function arguments during execution.
- In this code, the Heap would store:
 - The value 12 for the variable age.
 - The value 12 passed as an argument to the logAge function (stored in the ageArg memory location).

**Built-in Functions and Objects:**
- The code uses built-in functions like console.log. These functions are predefined and readily available for use.

**Type Information:**
JavaScript is loosely typed, so the engine doesn't explicitly store type information for variables. In this case, both age and ageArg would hold the numeric value 12.



## Conclusion
By understanding the JavaScript Execution Context and its components, you've gained valuable insight into how your code is processed and executed.  We've explored the creation and execution phases of the global execution context, as well as the creation and execution phases that occur within function calls. This knowledge helps you write more efficient and predictable JavaScript code.

Thanks for reading 😁😁😁😁