Search code examples
javascriptscopeiife

Why is one variable undefined outside of the IIFE while the other is not?


I was playing with IIFE and I'm confused. The value of a is undefined but b is not. Why am I able to access the value of b outside of IIFE?

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

console.log("a defined? " + (typeof a !== 'undefined')); // false
console.log("b defined? " + (typeof b !== 'undefined')); // true


Solution

  • Declaration syntax can be confusing, because it looks like the syntax for ordinary expressions. It is, however, different.

    var a = b = 3;
    

    is parsed as

    var a = (something);
    

    In this case, something is b = 3, so it's exactly as if your function looked like

    b = 3;
    var a = b;
    

    The "naked" b = 3 without var or let or const creates an implicit global variable. Thus b is visible outside the function, while a is not.