Log In

Don't have an account? Sign up now

Lost Password?

Sign Up

Prev Next

Module 6: Scope, Closures & Encapsulation

1. What is Scope?

Scope determines the accessibility (visibility) of variables. If a variable is “in scope,” you can use it; if it is “out of scope,” it is invisible.

A. Global Scope

Variables declared outside any function or curly braces {}. They are accessible from anywhere in your code.

B. Function (Local) Scope

Variables declared inside a function are local to that function.

JavaScript

function sayName() {
    let name = "Gemini"; // Function Scope
}
// console.log(name); // ReferenceError: name is not defined

C. Block Scope (ES6)

Variables declared with let and const inside { } (like if statements or loops) cannot be accessed outside the block.

Note: var does not have block scope.


2. Lexical Environment & Scope Chain

JavaScript uses Lexical Scoping. This means the “physical” location of where you wrote the code determines where variables are available.

When you try to access a variable, JS looks in the current scope. If it doesn’t find it, it looks in the Outer (Parent) Scope. This continues until it reaches the Global Scope. This “climbing” is called the Scope Chain.


3. Closures: The “Secret Memory”

A Closure is a function that “remembers” its lexical environment even when that function is executed outside of its original scope.

The simplest way to think of it: A function + its bundled variables.

Example of a Closure:

JavaScript

function outer() {
    let count = 0; // "outer" variable
    
    function inner() {
        count++; // "inner" can see "count"
        console.log(count);
    }
    
    return inner; 
}

const myCounter = outer(); 
myCounter(); // 1
myCounter(); // 2

What happened? Usually, when outer() finishes, its variables are deleted. But because inner was returned and still needs count, JS keeps count alive in memory. This is a closure!


4. Practical Use: Encapsulation (Private Variables)

In many languages, you have a private keyword. JS doesn’t (historically), so we use closures to hide data from the outside world. This is called Encapsulation.

JavaScript

function createBankAccount(initialBalance) {
    let balance = initialBalance; // Private variable

    return {
        deposit: function(amount) {
            balance += amount;
            console.log(`Balance: ${balance}`);
        },
        withdraw: function(amount) {
            if (amount > balance) return "Insufficient funds";
            balance -= amount;
            return `Remaining: ${balance}`;
        }
    };
}

const myAccount = createBankAccount(100);
myAccount.deposit(50); // Balance: 150
console.log(myAccount.balance); // undefined (The variable is hidden!)

5. The “Loop & Var” Gotcha

A classic interview question involves closures and loops.

The Buggy Code:

JavaScript

for (var i = 1; i <= 3; i++) {
    setTimeout(function() {
        console.log(i);
    }, 1000);
}
// Output after 1 second: 4, 4, 4 (Because var is not block-scoped)

The Fix: Change var to let. Because let is block-scoped, it creates a new closure (a new i) for every single iteration of the loop.


Technical Code Example: Data Privacy Pattern

JavaScript

const secretAgent = (function() {
    let secret = "007"; // Hidden from global scope

    return {
        getSecret: () => secret,
        setSecret: (newSecret) => { secret = newSecret }
    };
})();

console.log(secretAgent.getSecret()); // "007"
secretAgent.setSecret("99");


In Simple words :

1. Introduction

Modern software relies on:

  • Correct variable visibility (Scope)
  • State preservation (Closures)
  • Data protection (Encapsulation)

This module explains how data lives, who can access it, and how to protect it.


2. Scope

What is Scope?

Scope defines where a variable can be accessed in a program.

In simple words:
“Who can see this variable?”


3. Types of Scope

1. Global Scope

  • Declared outside all functions/classes
  • Accessible everywhere

Example:

int totalUsers = 100;

Overuse leads to bugs and tight coupling.


2. Local Scope

  • Declared inside a function or block
  • Exists only there

Example:

function calculate() {
   int sum = 0;
}

3. Block Scope

  • Variables declared inside { }
  • Common in loops and conditionals

Example:

if (x > 0) {
   int temp = x;
}

4. Function Scope

  • Variables accessible anywhere inside the function

(Common in JS using var)


5. Lexical (Static) Scope

  • Scope determined by code structure
  • Inner functions access outer variables

Key concept for closures.


4. Scope Chain

What is Scope Chain?

When a variable is not found in current scope, the language:

  1. Looks in parent scope
  2. Continues until global scope
  3. Throws error if not found

This lookup path is called the scope chain.


5. Common Scope Problems

  • Variable shadowing
  • Accidental global variables
  • Memory leaks
  • Unexpected value overrides

6. Closures

What is a Closure?

A closure is created when:

A function remembers and accesses variables from its outer scope, even after the outer function has finished execution.


Simple Definition

“Function + its surrounding data”


Example (Conceptual)

function outer() {
   int x = 10
   function inner() {
      print(x)
   }
   return inner
}

Even after outer() ends, inner() remembers x.


7. Why Closures Are Powerful

  • Preserve state
  • Data hiding
  • Function factories
  • Callbacks & event handlers

8. Real-World Use Cases of Closures

  • Counters
  • Caching
  • Authentication tokens
  • Private variables
  • Debouncing & throttling (JS)

9. Closures & Memory

  • Closures keep variables in memory
  • Can cause memory leaks if misused
  • Garbage collection occurs only when closure is released

10. Encapsulation

What is Encapsulation?

Encapsulation means bundling data and methods together and restricting direct access to data.

One of the four pillars of OOP:

  1. Encapsulation
  2. Abstraction
  3. Inheritance
  4. Polymorphism

11. Why Encapsulation Is Important

  • Protects data
  • Prevents misuse
  • Improves maintainability
  • Enhances modularity

12. Access Modifiers (OOP Languages)

ModifierAccess Level
publicEverywhere
privateSame class only
protectedSame class + subclass
defaultSame package

13. Encapsulation in Classes

Example (Conceptual):

class Account {
   private balance
   public deposit()
   public getBalance()
}

Direct access to balance is blocked.


14. Encapsulation Without Classes

(Common in JavaScript & Python)

Using:

  • Closures
  • Naming conventions
  • Modules

Example:

function createAccount() {
   let balance = 0
   return {
      deposit: function(x) { balance += x },
      getBalance: function() { return balance }
   }
}

15. Scope vs Encapsulation

AspectScopeEncapsulation
PurposeVisibilityProtection
LevelLanguage featureDesign principle
UsageVariablesData & methods

16. Closures vs Encapsulation

Closures:

  • Preserve state
  • Enable data hiding

Encapsulation:

  • Restricts access
  • Ensures controlled interaction

Closures often implement encapsulation in non-OOP languages.

Leave a Comment

    🚀 Join Common Jobs Pro — Referrals & Profile Visibility Join Now ×
    🔥