Search code examples
javascriptiife

Accessing variables within IIFE


I'm trying to learn module patterns and I've come across this scenario with IIFE and accessing internal variables.

var foo = (function () {
    var bar = false;

    function switchbar () {
     if(bar){ bar = false} else { bar = true } ; 
    };

    function show {
      switchbar();
      console.log(bar)
    };

   function noshow {
         switchbar();
         console.log(bar)
   };

   return {

     showTheBar: show,
     hideTheBar: noshow,
     whatIsBar: bar
   }
}());

foo.showTheBar()  //true
foo.whatIsBar //false  --> should be true

Why isn't bar true in the last output? Any insight would help alot. Thanks in advance.


Solution

  • The value of bar is assigned to the variable whatIsBar when the foo IIFE is executed. This new variable is no longer related to the value of the original bar.

    So whaterver bar is changed to, it wont affect whatIsBar. It is a completely different variable.