SmartCodingTips

Scope and Closures in JavaScript

Scope determines the visibility of variables. Closures allow functions to β€œremember” variables from their outer scope.

πŸ” JavaScript Scope

  • Global Scope – Variables declared outside any function
  • Function Scope – Variables declared inside a function using var
  • Block Scope – Introduced by let and const inside { }
let globalVar = "Global";

function testScope() {
    let functionVar = "Function";
    if (true) {
        let blockVar = "Block";
        console.log(blockVar); // βœ… Accessible here
    }
    // console.log(blockVar); ❌ Not accessible here
}

testScope();
// console.log(functionVar); ❌ Not accessible here

πŸ” Closures Explained

A closure is when an inner function accesses variables from an outer function even after the outer function has finished executing.

function outer() {
    let count = 0;

    return function inner() {
        count++;
        return count;
    };
}

const counter = outer();
console.log(counter()); // 1
console.log(counter()); // 2

πŸ’‘ Why Are Closures Useful?

  • Encapsulation – Keep variables private
  • Data persistence – Remember state across calls
  • Functional programming – Create factory functions
🧠 Tip: Closures power many JS patterns including callbacks, modules, and event handlers.