Types of Scope
1. Global Scopeâ
- Variables declared outside any function or block
- Accessible throughout the entire program
- Created using
var,let, orconstat the top level
const globalVar = "I'm global";
function testScope() {
console.log(globalVar); // Accessible
}
2. Function/Local Scopeâ
- Variables declared inside a function
- Only accessible within that function
- Each function creates its own scope
function myFunction() {
var localVar = "I'm local";
console.log(localVar); // Accessible
}
// console.log(localVar); // â Error: localVar is not defined
3. Block Scopeâ
- Variables declared inside a block
{} - Only accessible within that block
- Created using
letandconst(notvar)
if (true) {
let blockVar = "I'm block-scoped";
const alsoBlock = "Me too";
// Both accessible here
}
// console.log(blockVar); // â Error: blockVar is not defined
4. Lexical/Static Scopeâ
- Inner functions can access variables from outer scope
- Scope is determined by the location where variables are declared
function outer() {
const message = "Hello";
function inner() {
console.log(message); // Can access message
}
inner();
}