🔐 Scope of Variables
Last Updated: 22nd October 2025
Scope determines where a variable is accessible in your code.
- Global Scope – Accessible anywhere in the code.
- Local/Function Scope – Accessible only inside the function it is declared.
- Block Scope – Accessible only inside a block
{ }(forletandconst). - Lexical Scope – Accessible only inside a function or block.
Hinglish Tip 🗣: Scope ka matlab hai “variable ki visibility”. Jaise ek room ke andar rakha object sirf us room me dikhega (local), ghar ke bahar sab dekh sakte hain (global).
Global Scope
let globalVar = "I am global";
function showGlobal() {
console.log(globalVar);
}
showGlobal(); // "I am global"
console.log(globalVar); // "I am global"
Local/Function Scope
function greet() {
let localVar = "I am local";
console.log(localVar);
}
greet(); // "I am local"
console.log(localVar); // ReferenceError: localVar is not defined
Block Scope
if (true) {
let blockVar = "I am block scoped";
const blockConst = "Me too!";
var blockVarVar = "I am var"; // var is NOT block scoped
}
console.log(blockVar); // ReferenceError
console.log(blockConst); // ReferenceError
console.log(blockVarVar); // "I am var"
Hinglish Tip 🗣: var ka scope function tak hota hai, let aur const ka scope block tak hota hai.
Lexical Scope
Lexical Scope (static scope) means a function remembers the scope in which it was created, even if called elsewhere.
function outer() {
let outerVar = "I am outer";
function inner() {
console.log(outerVar);
}
return inner;
}
const innerFn = outer();
innerFn(); // "I am outer"
Here, inner can access outerVar even after outer has finished execution.
Hinglish Tip 🗣: Lexical scope ka matlab hai scope ka static behavior — functions ke andar ka access outer function ke variables ko yaad rakhta hai.