Thuta Learning
AdvancedProgrammingbeginner

Hoisting

Relax. We'll talk through this in plain words — no textbook voice.

Hoisting is the behavior where JavaScript moves variable and function declarations to the top of their scope.

📌 Rules:

• var: Hoisted, initialized as undefined

• let/const: Hoisted, but not initialized (TDZ)

• Function declarations: Fully hoisted

• Function expressions: Not hoisted

javascript
// Variable hoisting
console.log(x); // undefined (not error)
var x = 5;
console.log(x); // 5

// This is what happens:
// var x; // hoisted
// console.log(x); // undefined
// x = 5;

// let/const - Temporal Dead Zone
try {
    console.log(y);
    let y = 10;
} catch(e) {
    console.log("Error: Cannot access before initialization");
}

// Function hoisting
sayHello(); // Works!
function sayHello() {
    console.log("Hello from hoisted function!");
}

// Function expression - NOT hoisted
try {
    sayBye(); // Error
    const sayBye = function() {
        console.log("Bye!");
    };
} catch(e) {
    console.log("Function expression not hoisted");
}
You should see
undefined 5 Error: Cannot access before initialization Hello from hoisted function! Function expression not hoisted