HOISTING IN JS: The behavior where JavaScript moves the declarations of variables, functions, and classes to the top of their scope during the compilation phase.
- Hoisting applies to variable and function declarations.
- Initializations are not hoisted, they are only declarations.
- 'var' variables are hoisted with undefined, while 'let' and 'const' are hoisted but remain in the Temporal Dead Zone until initialized.
TYPES OF HOISTING:
- Variable Hoisting with var.
- Variable Hoisting with let and const.
- Function Declaration Hoisting.
- Function Expression Hoisting.
- Hoisting with let and const in Functions.
- Hoisting with Classes.
- Re-declaring Variables with var.
- Hoisted Functions with Parameters.
- Hoisting in Nested Functions.
VARIABLE HOISTING WITH VAR: Declaration is hoisted to the top, but its value is not assigned until the code execution reaches the variable’s initialization. This results in the variable being assigned undefined during the hoisting phase.
EXAMPLE:
console.log(i); //ERROR UNDEFINED
var i = 100;
VARIABLE HOISTING WITH LET AND CONSTANT: let and const are also hoisted, but they remain in a Temporal Dead Zone (TDZ) from the start of the block until their declaration is encountered. Accessing them before their declaration will throw a ReferenceError.
EXAMPLE:
console.log(i); //REFERENCE ERROR
let i = 200;
FUNCTION DECLARATION HOISTING: Hoisted with both their name and the function body. This means the function can be called before its definition in the code.
EXAMPLE:
greet();
function greet() {
console.log("Hello, VINOTH!");
}
FUNCTION EXPRESSION HOISTING: Expressions are treated like variable declarations. The variable itself is hoisted, but the function expression is not assigned until the line of execution. This means calling the function before its assignment will result in an error.
EXAMPLE:
hello(); // TYPERROR: hello is not a function
let hello = function() {
console.log("Hi!");
};


Top comments (0)