Scope determines where in your code a variable can be accessed.
🎯 Scope Types:
• Global Scope: Everywhere accessible
• Function Scope: Inside function only
• Block Scope: Inside {} (let/const)
• Lexical Scope: Nested functions access outer variables
javascript
// Global scope
let globalVar = "I'm global";
function demoScope() {
// Function scope
var functionVar = "I'm in function";
if (true) {
// Block scope
let blockVar = "I'm in block";
const alsoBlock = "Me too";
var notBlock = "I'm function scoped";
console.log(globalVar); // OK
console.log(functionVar); // OK
console.log(blockVar); // OK
}
console.log(functionVar); // OK
console.log(notBlock); // OK
// console.log(blockVar); // Error!
}
demoScope();
console.log(globalVar); // OK
// console.log(functionVar); // Error!
// Lexical scope
function outer() {
let outerVar = "outer";
function inner() {
let innerVar = "inner";
console.log(`${outerVar} + ${innerVar}`);
}
inner();
}
outer();You should see
I'm global I'm in function I'm in block I'm in function I'm function scoped I'm global outer + inner