Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

IIFE vs scope braces

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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 }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading