🌍 Scope in JavaScript
👉 Scope means: “where can I access a variable in my code?”
Get Harish Chirati’s stories in your inbox
Join Medium for free to get updates from this writer.
There are different kinds of scopes in JavaScript: Global, Function, Block, and Lexical.
Here, we’ll focus on Global Scope and Lexical Scope.
1️⃣ Global Scope
- A variable declared outside of any function/block is in the global scope.
- Accessible anywhere in the program.
- In browsers → attached to the
windowobject.
📌 Example:
let globalVar = "I am Global";
function showGlobal() {
console.log(globalVar); // ✅ Accessible
}
showGlobal();
console.log(globalVar); // ✅ Accessiblefunction showGlobal() {
console.log(globalVar); // ✅ Accessible
}2️⃣ Lexical Scope
- Lexical = “defined in source code (at writing time)”.
- Inner functions can access variables from their parent scope, even if called elsewhere.
- This rule enables closures.
📌 Example:
function outer() {
let outerVar = "I am from Outer";function inner() {
console.log(outerVar); // ✅ inner can access outerVar
} inner();
}outer();
function outer() {
let outerVar = "I am from Outer";
function inner() {
console.log(outerVar); // ✅ inner can access outerVar
}
inner();
}
outer();Here:
outerVaris not ininner()’s local scope.- But because of lexical scope,
inner()can access it.
3️⃣ ⚡ Key Difference
Scope TypeDefined ByAccessible Where?Global ScopeDeclared outside functions/blocksEverywhere in programLexical ScopeDetermined at code writing time by nestingInner functions can access outer scope variables
✅ Real-Life Example
let globalName = "Hari"; // Global Scope
function greet() {
let message = "Hello"; // Local to greet()
function display() {
// Lexical Scope: has access to parent function's variables
console.log(message + " " + globalName);
}
display();
}
greet(); // "Hello Hari"globalName → Global Scope
message→ Local togreet()display()→ Uses Lexical Scope to access bothmessageandglobalName





