Episode 22 of 46

Variable Scope

Understand how variable scope works — global, function, and block scope.

Scope determines where a variable can be accessed. Understanding scope prevents bugs and makes your code predictable.

Global Scope

Variables declared outside any function or block are global — accessible everywhere:

let globalVar = "I'm global!";

function test() {
    console.log(globalVar);  // Accessible here
}
test();
console.log(globalVar);  // Accessible here too

Function Scope

Variables declared inside a function are only accessible within that function:

function myFunction() {
    let localVar = "I'm local!";
    console.log(localVar);  // Works fine
}
myFunction();
// console.log(localVar);  // ERROR! Not defined outside

Block Scope (let and const)

let and const are block-scoped — they only exist within their { } block:

if (true) {
    let blockVar = "I'm block-scoped!";
    const anotherBlock = "Me too!";
    console.log(blockVar);  // Works
}
// console.log(blockVar);  // ERROR! Not defined outside the block

var is NOT Block-Scoped

if (true) {
    var oldVar = "I leak out!";
}
console.log(oldVar);  // "I leak out!" — var ignores blocks!

This is why we use let and const instead of var.

Scope Chain

let outer = "outer";

function outerFunc() {
    let middle = "middle";

    function innerFunc() {
        let inner = "inner";
        console.log(outer);   // Accessible (scope chain)
        console.log(middle);  // Accessible
        console.log(inner);   // Accessible
    }
    innerFunc();
}
outerFunc();