Definition: Scope determines where variables are accessible in your code.
- Think of scope as the visibility or lifetime of a variable.
- Helps avoid conflicts and controls how data is shared.
🔹 Types of Scope in JavaScript
1. Global Scope
- Variables declared outside of any function/block are in the global scope.
- Accessible everywhere in the program.
let globalVar = "I am global";
function test() {
console.log(globalVar); // ✅ Accessible here
}
test();
console.log(globalVar); // ✅ Accessible here too
2. Function Scope
- Variables declared inside a function are only available within that function.
- They cannot be accessed outside.
function example() {
let localVar = "I am inside function";
console.log(localVar); // ✅ Accessible here
}
example();
// console.log(localVar); ❌ Error: not defined
3. Block Scope (ES6)
- Variables declared with
letorconstinside{}are only available inside that block. vardoes not have block scope, only function scope.
if (true) {
let blockVar = "Inside block";
console.log(blockVar); // ✅ Accessible here
}
// console.log(blockVar); ❌ Error
4. Lexical Scope (Closures)
- Inner functions can access variables from their outer function (where they were created).
- This is called lexical scoping.
function outer() {
let outerVar = "Outer variable";
function inner() {
console.log(outerVar); // ✅ Can access parent's variable
}
inner();
}
outer();
🔹 Summary Table
| Scope Type | Declared With | Accessible Where? |
|---|---|---|
| Global Scope | Anywhere (outside fn) | Everywhere |
| Function Scope | var, let, const (inside fn) | Only inside that function |
| Block Scope | let, const (inside {}) | Only inside that block |
| Lexical Scope | Function inside another | Inner fn can access outer fn vars |