Functions & LogicSaturday, January 24, 2026

Scope & Hoisting

Where do your variables live?

Advertisement

Support JS Mastery Path by checking out our sponsors.

Scope is the set of rules that determines where your variables live and where they can be accessed. Hoisting is how the engine organizes them before running.

The One-Way Mirror Analogy

Think of scopes like Tinted Car Windows:
Inside-Out: If you are inside the car (Function Scope), you can see everything outside (Global Scope).
Outside-In: If you are outside, you cannot see what's happening inside the car. The variables inside are private.

The Scope Chain

When you use a variable, JavaScript looks for it in the current room. If it's not there, it looks in the outer room. It keeps going up until it hits the Global scope.

const globalUser = "Admin";

function outer() {
  const outerVar = "I am in the middle";
  
  function inner() {
    const innerVar = "I am deep inside";
    
    // 1. Looks in 'inner'? No.
    // 2. Looks in 'outer'? Yes! Found it.
    console.log(outerVar); 
    
    // 1. Looks in 'inner'? No.
    // 2. Looks in 'outer'? No.
    // 3. Looks in Global? Yes!
    console.log(globalUser);
  }
  
  inner();
}

outer();

Hoisting: The "Phantom" Variables

Hoisting isn't magic; it's the compiler doing a "first pass" to find all variable declarations before executing the code.

Variable behavior during Hoisting

  • function: Fully hoisted. You can call them before you define them.
  • var: Hoisted but initialized as undefined.
  • let / const: Hoisted but placed in the Temporal Dead Zone (TDZ). Touching them crashes the app.
// 1. Functions are safe to use early
sayHello(); 

function sayHello() {
  console.log("I work because I was hoisted!");
}

// 2. Var is dangerous
console.log(myVar); // undefined (Not an error, just empty)
var myVar = 10;

// 3. Let/Const explode
try {
  console.log(myLet);
} catch(e) {
  console.error("TDZ Error:", e.message);
}
let myLet = 20;
Advertisement

Support JS Mastery Path by checking out our sponsors.