Search code examples
javascriptfrontendweb-frontend

Javascript - need explanation on the variable inside IIFE


I have this code - I just wonder why after I add 'var' to foo variable, it doesn't work (it shows me foo is undefined)... Can anyone help explain these two functions? Thanks!

window.onload = function() {
    var test = foo().steps(2);
    console.log(test);
}

(function() {
  //if I remove var, then it prints out a function which is what I expected
  var foo = function() {
    var steps = 1;
    function callMe(g) {
      //do something else
      console.log("hello" + g);
    }
    callMe.steps = function(x) {
      //if no arguments then return the default value
      if (!arguments.length) return steps;
      console.log(arguments);
      //otherwise assign the new value and attached the value to callMe
      steps = x;
      return callMe;
    }
    return callMe;
  }
})();

Solution

  • adding var to foo makes foo a local variable inside the IIFE and thus you can't access it outside.