Before ES6 introduced let and const, JavaScript only had var for variable declarations. But var has one quirk — it doesn’t respect block scope.

What’s Block Scope?

Block scope means variables declared inside { } are only accessible within those curly braces.

{
  let x = 10;
}
console.log(x); // ReferenceError: x is not defined

But var doesn’t work like that:

{
  var y = 20;
}
console.log(y); // 20 — y is still accessible!

Why Is This a Problem?

If you use var inside a loop or conditional block, the variable is still accessible outside — which can lead to bugs.

Trick: Use an IIFE to Simulate Block Scope

An IIFE (Immediately Invoked Function Expression) creates a function that runs right away, creating a new scope.

(function () {
  var secret = 'hidden';
  console.log(secret); // hidden
})();

console.log(secret); // ReferenceError: secret is not defined

Example: Loop with IIFE

This prevents variable leaks in loops:

for (var i = 0; i < 3; i++) {
  (function(index) {
    setTimeout(function () {
      console.log(index);
    }, 100);
  })(i);
}

// Output: 0, 1, 2 — instead of 3, 3, 3

Why This Worked Back Then

  • Each IIFE creates a new function scope
  • Variables inside IIFE don’t leak outside
  • Great for managing scope before ES6

Modern Alternative: Just Use let

for (let i = 0; i < 3; i++) {
  setTimeout(() => console.log(i), 100);
}

This is cleaner and easier to read — thanks to block-scoped let.

Conclusion

Before ES6, JavaScript developers used IIFEs to simulate block scope and avoid bugs from var‘s function-level scope. Today, let and const offer real block scope, but understanding these older patterns can help you read legacy code and write safer JavaScript.

Post a Comment

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