Home > other >  IIFE vs scope braces
IIFE vs scope braces

Time:02-08

Perhaps this is the stupidest question, but for IIFE, it mentions being used as a scope that would not pollute the global namespace.

Why would that be necessary as opposed to just using braces by itself to delimit scope (like in C)? For example:

{
    let firstVariable = 1;
    let secondVariable = 2;
}
console.log(firstVariable);

Instead of:

(function () {
    let firstVariable = 1;
    let secondVariable = 2;
})();
console.log(firstVariable);

CodePudding user response:

JavaScript first appeared in 1995. The first specification edition was from 1997.

The specification that does include block scope is ES6 from 2015. Therefore, there has been no block scope for close to 20 years before it was introduced. IIFEs have existed in the mean time.

Also worth noting that block scope is not universal. It does work for let and const but not var

{
  var foo = 42;
}

console.log(foo);

(function() {
  var bar = 42;
})();

console.log(bar);

Functions are also block-scoped as of ES6 but the rules around that are weird.

console.log("---- foo ----");

console.log("before block", foo); //undefined
{
  function foo() { return 42; }
}
console.log("after block", foo); //function foo() { return 42; }


console.log("---- bar ----");

function bar() { return 1; }

console.log("before block", bar());   //output: 1
{
  function bar() { return 2; }
  console.log("inside block", bar()); //output: 2
}
console.log("after block ", bar());   //output: 2


console.log("---- baz ----");

{
  function baz() { return 1; }

  console.log("before inner block", baz());   //output: 1
  {
    function baz() { return 2; }
    console.log("inside inner block", baz()); //output: 2
  }
  console.log("after inner block ", baz());   //output: 1
}
.as-console-wrapper { max-height: 100% !important }

  •  Tags:  
  • Related