👉 Hoisting in JavaScript
- Hoisting is a JavaScript behavior where you can access variables, functions, and classes even before they are declared in the code, without encountering any errors.
👉 Variable Hoisting :
- Variables declared using var are hoisted and initialized to undefined During The Memory Creation Phase.
- When Variables declared with let and const are also hoisted, but they are not initialized In Global Scope Means Browser Window Object. let And const Variable Initialized undefined in script memory, leading to a "Temporal Dead Zone" .
👉 Temporal Dead Zone :
- When you declare variables with let and const, they are subject to the Temporal Dead Zone (TDZ). During the Memory Creation Phase of the execution context, let and const variables are initialized in the script's memory location but are not assigned a value. The TDZ refers to the period between when the variable enters the scope and when it is actually declared and initialized. During this time, any attempt to access the variable will result in a "Reference Error "
👉 Function Hoisting:
- Function declarations are hoisted entirely During the Memory creation Phase, That's why the function can be called before its declaration in the code.
- Function expressions are Also hoisted but it is treated as Variables and initialized to "undefined" In the Memory Creation Phase. If You Call This Function Before initialized it throw type Error that is “that Variable is not a Function “
👉 Class Hoisting:
- Class declarations are hoisted, but unlike functions, they are not initialized. This means you cannot instantiate a class before its declaration.
👉 Execution Context:
- Hoisting occurs in the memory allocation phase of the execution context. This is why we can use variables and functions before they are explicitly declared in the code.
👉 Undefined vs. Not Defined:
- undefined: A variable has been declared Memory Location Has been Allocates For Variables and but not yet assigned a value.
- not defined: A variable has not been declared at all. Means No Memory Location Allocates For Variables