some variables in JavaScript seem to work before they're even declared.
Types of Hoisting:
1.var is hoisted — with undefined as default value
console.log(a); // undefined
var a = 10;
2.let and const are hoisted — but not initialized
They are placed in a "Temporal Dead Zone (TDZ)" from the start of the block until their declaration is encountered.
console.log(b); // Reference Error
let b = 20;
3.Function Hoisting
!!Function declarations are hoisted with their full definition.
greet(); // works
function greet() {
console.log("Hello!");
}
Non-Hoisting Scenarios
1.let and const in Temporal Dead Zone:
console.log(num); // ReferenceError
let num = 10;
2. Arrow Functions with const or let:
add(3, 4); //ReferenceError
const add = (a, b) => a + b;
Only const add; is hoisted, not the function definition.
3.Class Declarations
const obj = new MyClass(); // ReferenceError
class MyClass {
constructor() {
this.name = "JS";
}
}
let’s meet again in the next topic
Top comments (0)