1. Function Scope
- Variables declared inside a function are accessible anywhere within that function (and its inner functions), but not outside.
varin JavaScript is function-scoped.- Example:
function test() {
var x = 10; // function scoped
if (true) {
var y = 20; // still function scoped
}
console.log(x); // ✅ 10
console.log(y); // ✅ 20 (accessible even outside the if block)
}
test();
// console.log(x); ❌ Error (x not accessible outside function)
2. Block Scope
- Variables declared inside a block
{}(likeif,for,while,{}) are only accessible within that block. letandconstare block-scoped.- Example:
function test() {
let a = 10; // block scoped to function
if (true) {
let b = 20; // block scoped to this if
const c = 30; // block scoped to this if
console.log(a); // ✅ 10
console.log(b); // ✅ 20
console.log(c); // ✅ 30
}
console.log(a); // ✅ 10
// console.log(b); ❌ Error (b is block scoped)
// console.log(c); ❌ Error (c is block scoped)
}
test();
✅ Key Differences
| Feature | Function Scope | Block Scope |
|---|---|---|
| Keyword | var | let, const |
| Visibility | Accessible throughout the function, even outside blocks | Accessible only within the enclosing {} block |
| Common Issue | Leads to accidental variable leakage | Safer and more predictable |
👉 In short:
- Function scope (
var) → whole function. - Block scope (
let,const) → just the{}block.
