Chapter 06 โ€” Scope (Global, Function, Block)

๐Ÿ“– Definition

Scope defines the region of a program where a variable is accessible.

๐Ÿ” Explanation

JavaScript uses lexical (static) scoping โ€” scope is determined by where code is written, not where it is called.

Scope Created by Holds
Global Top of the script var / let / const at the top level
Function Any function body var, let, const, parameters
Block {} of if, for, while, etc. Only let and const
Module An ES module file Top-level declarations are module-scoped (not global)

๐Ÿ’ป Code Example โ€” Function vs Block Scope

function test() {
  if (true) {
    var a = 1;                 // function-scoped
    let b = 2;                 // block-scoped
    const c = 3;               // block-scoped
  }
  console.log(a);              // 1  โœ…
  console.log(b);              // โŒ ReferenceError
  console.log(c);              // โŒ ReferenceError
}

๐Ÿ’ป Code Example โ€” Lexical (Static) Scoping

let x = "global";

function outer() {
  let x = "outer";
  function inner() {
    console.log(x);            // "outer" โ€” lexical lookup
  }
  inner();
}
outer();

Even if inner() is called from somewhere else, it still resolves x to "outer", because that's where it was defined.

๐Ÿ’ป Code Example โ€” Scope Chain

const a = 1;
function f1() {
  const b = 2;
  function f2() {
    const c = 3;
    console.log(a, b, c);      // 1 2 3 โ€” walks up the chain
  }
  f2();
}
f1();

๐Ÿ’ป Code Example โ€” Module Scope

// math.js
export const PI = 3.14;        // module-scoped, NOT global
const internal = "private";    // not exported โ†’ invisible outside

// app.js
import { PI } from "./math.js";
console.log(PI);               // 3.14
console.log(internal);         // โŒ ReferenceError

๐Ÿ’ป Code Example โ€” Block Scope Saves Loops

// var leaks out
for (var i = 0; i < 3; i++) {}
console.log(i);                // 3 โ€” leaked

// let stays inside
for (let j = 0; j < 3; j++) {}
console.log(j);                // โŒ ReferenceError

๐ŸŒ Real-World Impact

  • Prefer const everywhere; use let only when reassignment is needed; avoid var.
  • Modules give natural encapsulation โ€” your "private" helpers stay private if you don't export them.

๐ŸŽฏ Likely Interview Questions

  1. What's the difference between function and block scope?
  2. What is lexical scoping?
  3. Why is var considered dangerous? โ€” Function-scoped (not block-scoped), hoisted to undefined, can leak out of loops/blocks.
  4. Scope chain explained.
  5. Output prediction:
    function outer() {
      const greeting = "hi";
      return function () { console.log(greeting); };
    }
    const fn = outer();
    fn(); // "hi" โ€” closure preserves outer scope

โ† Hoisting | Index | Next: this Keyword โ†’