Why pass in window as parameter?

If window is a global variable, why do we pass it in the IIFEs? Why can’t we invoke a function with no arguments?

Also, we use the line

var App = window.App || {};

Hi @ballgeier, did you figure this out? Depending on which copy of the book you have, I can point you to the relevant pages which (hopefully) explain the reasoning more succinctly than me :smiley:

I would like to know the answer to ballgeier’s question so if you can elaborate. He makes a good point that I completely overlooked as I was going through the lessons - if the window is a global object, why do we need to pass it into the IIFE? Does the IIFE not have scope to the global window object?

Hi @JSLearner, the IIFE does have access to the global window object, however we’re showing a pattern called Parameter Mapping / Dependency Injection. A good example is, say, allowing your code to work with both jQuery and Zepto (a lightweight alternative with the same API).

If I had this code:

var $main = jQuery('body > .main');
$main.append('hello');

It is tightly coupled to jQuery. But what if I wanted to swap in Zepto? Then I’d have to replace all occurrences of jQuery. However, with the IIFE param mapping pattern, I could do this instead:

(function($) {

  var $main = $('body > .main');
  $main.append('hello');

})(window.jQuery || window.zepto)

Now our code will work with Zepto or jQuery loaded! BTW this is a common technique for squeezing better performance out of your website.

Essentially, this pattern allows you to write code that is not tightly coupled to the environment and what libraries are in scope. That means you can write code with different libraries, or even run it in a completely different environment (like pre-rendering a page on a Node.js server to speed things up).

In this particular case, we are treating the window global as a sort of dependency. By mapping this way, we can write code that will run in the browser or in Node.js (where we don’t have window, but instead have globals).

Thank you. Still a bit advance of a subject matter but I"ll get it in due time…