How Global Execution Context and Temporal Dead Zone Work in JavaScript

How Global Execution Context and Temporal Dead Zone Work in JavaScript
# Understanding JavaScript Execution Context, Hoisting & Temporal Dead Zone (TDZ)

Have you ever wondered **how JavaScript runs your code behind the scenes**, how the **Global Execution Context (GEC)** works, and why variables behave differently with `var`, `let`, and `const`?  
Let's break it all down step-by-step.

---

## Example Code

console.log('My age is', age)

console.log('My name is', name)

console.log('My country is', country)

var age = 24

let name = 'Shejan'

const country = 'Bangladesh'

sayHi()

function sayHi() {

console.log('Hi!')

}


---

## Expected Output Analysis

1. **Line 1**:  
   Prints: `My age is undefined`  
   Reason: `var` gets hoisted and initialized with `undefined`.

2. **Line 2**:  
   Throws:  

ReferenceError: Cannot access 'name' before initialization

   Reason: `let` is hoisted but remains **uninitialized** within the **Temporal Dead Zone (TDZ)** until its declaration.

3. **Line 3**:  
   Will not execute because execution stops at the ReferenceError in line 2.  
   If line 2 were removed, line 3 would throw the same error for `const`.

4. **Function `sayHi()`**:  
   Fully hoisted with its body, so calling it before its definition works — **if** execution reaches that point.

---

## Topics to Cover
- [Global Execution Context](#global-execution-context)
- [Memory Creation Phase](#memory-creation-phase)
- [Code Execution Phase](#code-execution-phase)
- [Hoisting Behavior](#hoisting-behavior)
- [`var` vs `let` vs `const`](#var-vs-let-vs-const)
- [Temporal Dead Zone (TDZ)](#temporal-dead-zone-tdz)
- [Function Hoisting](#function-hoisting)
- [Key Takeaways](#key-takeaways)

---

## Global Execution Context

When JavaScript runs your code:

1. **Memory Creation Phase** – Allocates variables and functions in memory before any code executes.
2. **Code Execution Phase** – Executes your code line-by-line using the pre-allocated memory.

---

## Memory Creation Phase

During this phase:

- **`var`** → Hoisted, initialized to `undefined`.
- **`let`**, **`const`** → Hoisted, **uninitialized**, placed in TDZ until declaration.
- **Function declarations** → Fully hoisted with their body.

Example memory allocation for our code:

age: undefined

name:

country:

sayHi: function() { console.log("Hi!"); }


---

## Code Execution Phase

1. **`console.log("My age is", age);`** → Finds `age` in memory (`undefined`).
2. **`console.log("My name is", name);`** → Finds `name` in TDZ → throws ReferenceError.
3. Code stops here; `country` and `sayHi()` never run.

If `name` and `country` log statements were removed:
- Variables get assigned (`age = 24`, `name = "Shejan"`, `country = "Bangladesh"`).
- `sayHi()` runs because the function was already loaded into memory.

---

## Hoisting Behavior

**Hoisting** = Moving declarations to memory before execution starts.  
Different types behave differently.

| Declaration Type     | Hoisted | Initialized | Accessible Before Declaration? |
|----------------------|---------|-------------|---------------------------------|
| `var`                | ✅      | `undefined` | Yes (returns `undefined`)       |
| `let`                | ✅      | No (TDZ)    | ❌ ReferenceError                |
| `const`              | ✅      | No (TDZ)    | ❌ ReferenceError                |
| Function Declaration | ✅      | With body   | ✅                               |

---

## `var` vs `let` vs `const`

### `var`

console.log(name) // undefined

var name = 'Rahim'

console.log(name) // "Rahim"


### `let`

console.log(name) // ReferenceError

let name = 'Rahim'

console.log(name) // "Rahim"


### `const`

console.log(age) // ReferenceError

const age = 24

console.log(age) // 24


---

## Temporal Dead Zone (TDZ)

The **TDZ** is the period between entering scope and the variable's declaration line.

Example:

console.log(x) // ReferenceError

let x = 10

console.log(x) // 10


Purpose: Prevents access before declaration → safer code.

---

## Function Hoisting

### Function Declarations

greet() // "Hello World!"

function greet() {

console.log('Hello World!')

}

✅ Works because both name and body are hoisted.

### Function Expressions

greet() // TypeError: greet is not a function

var greet = function() { console.log('Hello World!') }

❌ Only variable name hoisted → initialized to `undefined`.

### Arrow Functions
Behave like function expressions regarding hoisting:

sayHello() // ReferenceError

const sayHello = () => { console.log('Hello!') }


---

## Key Takeaways

- **All declarations are hoisted**, but initialization differs.
- **Function declarations**: call anytime before definition.
- **Function expressions/arrow functions**: follow variable rules.
- **TDZ**: Enforces safer code — access after declaration only.
- Understanding the two phases (memory creation, code execution) is essential for debugging and predictable coding.

---

## Visual Recap
1. **Memory Phase** — JavaScript inventories *what* exists.
2. **Execution Phase** — JavaScript runs in order, using prepared memory.
3. Errors occur (`ReferenceError`, `TypeError`) when accessing variables/functions before they’re properly initialized.

---

## Bonus for Content Creators

If you create **technical guides like this** and want to share them widely, tools like **[AiToEarn官网](https://aitoearn.ai/)** can help:

- AI-assisted content drafting
- Publish once to multiple platforms (Douyin, Kwai, WeChat, Bilibili, Rednote, Facebook, Instagram, LinkedIn, Threads, YouTube, Pinterest, X)
- Integrated analytics
- AI model ranking ([AI模型排名](https://rank.aitoearn.ai))
- Open-source: [AiToEarn GitHub](https://github.com/yikart/AiToEarn)

This lets you focus on **creating** while the system handles distribution and optimization — like the way JS prepares code in memory before execution.

---

**Happy coding!**  
Master hoisting, TDZ, and execution contexts, and your JavaScript will be as predictable as you are.

Read more