HomeJAVASCRIPTWhat is the difference between function scope and block scope?

What is the difference between function scope and block scope?

1. Function Scope

  • Variables declared inside a function are accessible anywhere within that function (and its inner functions), but not outside.
  • var in 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 {} (like if, for, while, {}) are only accessible within that block.
  • let and const are 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

FeatureFunction ScopeBlock Scope
Keywordvarlet, const
VisibilityAccessible throughout the function, even outside blocksAccessible only within the enclosing {} block
Common IssueLeads to accidental variable leakageSafer and more predictable

👉 In short:

  • Function scope (var) → whole function.
  • Block scope (let, const) → just the {} block.

Share: 

No comments yet! You be the first to comment.

Leave a Reply

Your email address will not be published. Required fields are marked *