Search code examples
javascriptvariife

Javascript chained variable assignments declared inside IIFE gets global visibility?


Was recently asked what the following JavaScript code would result in and the correct answer confuses me:

(function () {
    var a = b = 5;
})();
console.log(b);

I would have thought this would print undefined but it actually prints 5.

From my understanding, all variables defined inside IIFE (Immediately Invoked Function Expression) should not be visible outside its scope. How exactly does the ordering of these variable declarations make b visible outside its scope while a is not visible outside its scope?


Solution

  • This:

    var a = b = 5;
    

    Is equivalent to:

    b = 5;
    var a = b;
    

    not to

    var b = 5;
    var a = b;
    

    It creates b as a global, and then assigns the value of b to a.

    It is also forbidden in strict mode. Always use strict mode!

    "use strict";
    
    (function () {
        var a = b = 5;
    })();
    console.log(b);