Hoisting refers to the behaviour where JavaScript moves the declarations of variables, functions, and classes to the top of their scope during the compilation phase. This can sometimes lead to surprising results, especially when using var, let, const, or function expressions.
- 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.
Temporal Dead Zone (TDZ) :
It refers to the period between the entering of a scope (such as a function or block) and the actual initialization of a variable declared with let or const. During this time, any reference to the variable before its initialization will throw a ReferenceError.
- Variables declared with let and const are hoisted to the top of their scope, but they are not initialized until their declaration line is reached.
- Any attempt to access these variables before their declaration will result in an error.
- The TDZ exists only for variables declared using let and const. Variables declared with var do not have this issue, as they are hoisted and initialized to undefined.
var (Function / Global)
var avoids TDZ because it is initialized as undefined during hoisting.
let & const (Block)
let and const are not initialized until their declaration line, so TDZ applies.
Variable Hoisting with var
When you use var to declare a variable, the 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.
console.log(a); // undefined
var a = 5;
Variable Hoisting with let and const
Unlike var, 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.
console.log(b); // ReferenceError: Cannot access 'b' before initialization
let b = 10;
Function Declaration Hoisting
Function declarations are hoisted with both their name and the function body. This means the function can be called before its definition in the code.
greet(); // "Hello, world!"
function greet() {
console.log("Hello, world!");
}
Function Expression Hoisting
Function 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.
hello(); // TypeError: hello is not a function
var hello = function() {
console.log("Hi!");
};
Reference Link
https://www.geeksforgeeks.org/javascript/javascript-hoisting/
Top comments (0)