Deep Dive into Function Execution and Hoisting in JavaScript

we're exploring how functions execute in JavaScript and the fascinating concept of hoisting, which allows functions to be accessible throughout your code even before they’re defined. We’ll also discuss a critical concept called the Temporal Dead Zone (TDZ), which can affect variables declared with let and const.

Note: 📝 Don’t worry if the term “Temporal Dead Zone (TDZ)” is new — we’ll explain it in simple terms below.

📜 Hoisting in JavaScript

Hoisting is the behavior where function and variable declarations are moved to the top of their scope during the memory allocation phase.

🧠 How Hoisting Works in JavaScript

JavaScript executes code in two main phases:

  1. Memory Allocation Phase — Memory is allocated for variables and functions.
  2. Code Execution Phase — Code runs line-by-line.

⏳ Memory Allocation Phase

In this phase, JavaScript prepares memory for variables and functions.

    
    let sum = add(5, 10); // sum is assigned the result of add(5, 10)

    function add(a, b) {
        return a + b;
    }
    
    

🔍 Memory after Allocation Phase:

Variable / FunctionValueState
addFunction (a, b) => a + bAvailable for use
sumTDZ (not initialized)Inaccessible in TDZ

⚡ Temporal Dead Zone (TDZ)

The TDZ is the period between a variable’s hoisting and its initialization. Accessing a variable in the TDZ causes a ReferenceError.

    
    console.log(value); // ❌ ReferenceError
    let value = 10;
    
    

🕰️ Code Execution Phase

Once memory allocation is complete, JavaScript executes the code line-by-line.

Example of function execution:

    
    let sum = add(5, 10); // function call
    function add(a, b) {
        return a + b;
    }
    console.log(sum); // ✅ Output: 15
    
    

🧩 Final State in Memory After Execution:

Variable / FunctionValue
add(a, b) => a + b
sum15

🏆 Key Takeaways

🚀 Next Steps

Now that you understand function declarations, it’s time to explore:

Each brings unique behaviors and power to JavaScript. Keep learning and practice writing different types of functions to master this concept! 💪