Scope & Closures
What is Scope?
Scope determines where variables are accessible in JavaScript. There are three types of scope.
- Global Scope: Variables declared outside any function are available everywhere.
- Function Scope: Variables declared inside a function are only available within that function.
- Block Scope: Variables declared with let or const inside a block `{}` are only accessible inside that block.
let globalVar = "I am global";
function example() {
let functionVar = "I exist inside this function";
if (true) {
let blockVar = "I exist inside this block";
console.log(blockVar); // Works
}
console.log(functionVar); // Works
console.log(blockVar); // Error (blockVar is not accessible here)
}
console.log(globalVar); // Works