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.
Variables declared outside any function or curly braces {}. They are accessible from anywhere in your code.
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
Variables declared with let and const inside { } (like if statements or loops) cannot be accessed outside the block.
Note:
vardoes not have block scope.
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.
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.
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!
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!)
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.
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");
Modern software relies on:
This module explains how data lives, who can access it, and how to protect it.
Scope defines where a variable can be accessed in a program.
In simple words:
“Who can see this variable?”
Example:
int totalUsers = 100;
Overuse leads to bugs and tight coupling.
Example:
function calculate() {
int sum = 0;
}
{ }Example:
if (x > 0) {
int temp = x;
}
(Common in JS using var)
Key concept for closures.
When a variable is not found in current scope, the language:
This lookup path is called the scope chain.
A closure is created when:
A function remembers and accesses variables from its outer scope, even after the outer function has finished execution.
“Function + its surrounding data”
function outer() {
int x = 10
function inner() {
print(x)
}
return inner
}
Even after outer() ends, inner() remembers x.
Encapsulation means bundling data and methods together and restricting direct access to data.
One of the four pillars of OOP:
| Modifier | Access Level |
|---|---|
| public | Everywhere |
| private | Same class only |
| protected | Same class + subclass |
| default | Same package |
Example (Conceptual):
class Account {
private balance
public deposit()
public getBalance()
}
Direct access to balance is blocked.
(Common in JavaScript & Python)
Using:
Example:
function createAccount() {
let balance = 0
return {
deposit: function(x) { balance += x },
getBalance: function() { return balance }
}
}
| Aspect | Scope | Encapsulation |
|---|---|---|
| Purpose | Visibility | Protection |
| Level | Language feature | Design principle |
| Usage | Variables | Data & methods |
Closures:
Encapsulation:
Closures often implement encapsulation in non-OOP languages.