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.
Hoisting is the behavior where function and variable declarations are moved to the top of their scope during the memory allocation phase.
undefined.JavaScript executes code in two main phases:
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 / Function | Value | State |
|---|---|---|
| add | Function (a, b) => a + b | Available for use |
| sum | TDZ (not initialized) | Inaccessible in 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;
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 / Function | Value |
|---|---|
| add | (a, b) => a + b |
| sum | 15 |
var = undefined, let/const in TDZ.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! 💪