Home Courses Lexical Scope Explained - Scope Rules and Closure Example

Lexical Scope Explained - Scope Rules and Closure Example

Lexical scope means that the scope of a variable is determined by where it is written in the code, not where the function is executed.


What is Scope?

Scope defines:

  1. Where a variable is accessible
  2. Where it exists in the program

If a variable is not accessible somewhere, you may see:


undefined or ReferenceError

Definition 2:

A function can access:

  1. Its own variables
  2. Its parent function’s variables
  3. Global variables

This behavior is called Lexical Scope.


Basic Example


let a = 10;

function outer() {
let b = 20;
console.log(a, b);

function inner() {
let c = 30;
console.log(a, b, c);
}

inner();
}

outer();

Output:

10 20
10 20 30


Explanation

  1. inner() can access:
  2. c (its own variable)
  3. b (parent variable)
  4. a (global variable)
  5. But the reverse is NOT possible:
  6. outer() cannot access c
  7. Global scope cannot access b or c

Important Rules of Lexical Scope

  1. Scope is decided by where the function is written, not where it is called
  2. JavaScript follows lexical (static) scoping
  3. Child functions can access parent and global variables
  4. Parent cannot access child variables
  5. This behavior enables closures


Example Showing Scope Limitation


let a = 10;

function outer() {
let b = 20;
console.log(a, b);
}

outer();
console.log(b); // Error: b is not defined


Lexical Scope + Closure Example


function greet(msg) {
return function (name) {
console.log(msg, name);
};
}

const sayHello = greet("Hello");
sayHello("Sidhu");

Output:

Hello Sidhu


Explanation

  1. greet("Hello") executes first
  2. It returns a function
  3. That returned function still remembers msg
  4. This is closure, enabled by lexical scope


Real Understanding

Lexical scope defines:

  1. How variables are accessed

Closure uses that behavior to:

  1. Remember variables even after execution


Why Lexical Scope is Important

Used in:

  1. Closures
  2. Callbacks
  3. Event handlers
  4. Functional programming
  5. Modular code design



Share this lesson: