Search code examples
javascriptiife

variables from IIFE accessible in global scope


how come the output of this IIFE is 5?

(function() {
  var a = b = 5;
})();

console.log(b);

I tried console.log(a) but it gives a reference error as expected how come 'b' is alive in global scope?


Solution

  • Interesting question. Though it is not related to IIFE's or hoisting at all. Notice how "a" is not defined!

    Your code sample

    function test() {
      var a = b = 5;
    }
    

    is semantically equivalent to this:

    function test() {
      var a = 5;
      // this is essentially the same as `window.b = a`
      b = a;
    }
    

    since you did not declare "a" (aka var a;) it ends up in the global scope. In strict mode this would not work.