π 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
Top comments (2)
Great cheat sheet for the topic of hoisting. Thanks!
Thank you