Scope (Global, Function, Block)
Scope determines where variables are accessible. Understanding scope is crucial for avoiding bugs where variables unexpectedly change or become undefined. JavaScript has three scope levels: global, function, and block.
Scope Levels
- Global scope — Variables declared outside any function/block. Accessible everywhere. Avoid polluting global scope
- Function scope — Variables declared inside a function. Only accessible inside that function
- Block scope — Variables declared with let/const inside { }. Only accessible inside that block (if, for, while)
- var — Has function scope only (leaks out of blocks!). This is why we avoid var
- Scope chain — Inner scopes can access outer scope variables, but NOT the other way around
- Lexical scope — Scope is determined by where code is WRITTEN, not where it runs
Scope Code
// Global scope
const appName = "Priygop"; // accessible everywhere
function showApp() {
console.log(appName); // ✅ can access global
}
showApp();
// Function scope
function greet() {
const greeting = "Hello"; // only inside greet()
console.log(greeting); // ✅
}
greet();
// console.log(greeting); // ❌ ReferenceError!
// Block scope (let/const)
if (true) {
const blockVar = "I'm in a block";
let blockLet = "Me too";
var leaks = "I leak out!";
console.log(blockVar); // ✅
}
// console.log(blockVar); // ❌ ReferenceError (const is block-scoped)
// console.log(blockLet); // ❌ ReferenceError (let is block-scoped)
console.log(leaks); // ✅ "I leak out!" (var ignores blocks!)
// Scope chain — inner accesses outer
const outer = "I'm outer";
function outerFn() {
const middle = "I'm middle";
function innerFn() {
console.log(outer); // ✅ accesses global
console.log(middle); // ✅ accesses parent function
}
innerFn();
}
outerFn();Tip
Tip
Keep your global scope clean — wrap code in functions or modules. Every global variable risks naming collisions with other scripts or libraries. Use IIFE or ES modules to create isolated scopes.
JavaScript looks outward through the scope chain to find variables
Common Mistake
Warning
Accidentally creating global variables by forgetting let/const. Writing x = 10 without a keyword creates a global variable (in non-strict mode). Always use 'use strict' or let/const to prevent accidental globals.
Practice Task
Note
Test scope behavior: (1) Declare a variable inside an if block with let and try accessing it outside — observe the error. (2) Do the same with var and see it leak. (3) Create a function that accesses a variable from its parent scope (scope chain).
Quick Quiz
Key Takeaways
- Scope determines where variables are accessible.
- Global scope — Variables declared outside any function/block. Accessible everywhere. Avoid polluting global scope
- Function scope — Variables declared inside a function. Only accessible inside that function
- Block scope — Variables declared with let/const inside { }. Only accessible inside that block (if, for, while)