Question

I just saw this question into which someone passed window.Module = window.Module || {} into a function.

For example:

(function(module){
    // do something with module
})(window.Module = window.Module || {});

I understand that if window.Module is undefined (or false for that matter) then {} would be passed in, but what is the point in setting window.Module equal to itself?


For people posting answers:

I read the code as:

if(!(window.Module = window.Module)) {
     // pass {} into function
}
else {
     // pass window.Module = window.Module into function 
     // (which makes NO sense to me)
}
Was it helpful?

Solution

That bit does two things:

  1. The window.Module || {} bit uses JavaScript's curiously-powerful || operator to evaluate to either window.Module (if it's truthy) or {} (if window.Module is falsey). || evalutes to its first non-falsey operand. Then the result of that is assigned to window.Module. The result is that if window.Module was falsey (probably undefined), it gets {} assigned to it; if it wasn't falsey (it probably already refers to an object), in theory it gets reassigned to itself although in practice engines are probably smart enough not to bother with the dead store.

  2. Then it passes the result of the assignment (the value [now] in window.Module) into the function.

So the end result is that window.Module is set to a new blank object if it wasn't set before, and regardless of whether it was set before, whatever object is (now) in window.Module is passed into the function.

OTHER TIPS

This confusion is why I'm not a fan of the short-circuit expression over a simple if.

Expressed using a conventional structure:

if (!window.Module)
{
    window.Module = {};
}
else
{
    // this is a no-op, and the whole else clause could be removed.
    window.Module = window.Module;
}

You can't use this structure in an expression, but it is more readable.

The main reason it's assigning window.Module is to be sure it's assigned. You could simply pass window.Module || {}, but that would leave it uninitialized.

(function(module){
    // do something with module
})(window.Module = window.Module || {});

This code first makes sure that a global Module object is set, and then passes it into the function. If you left out the assignment:

(function(module){
    // do something with module
})(window.Module || {});

then Module would not be set (if it didn't exist at that point). Of course, module can be used to access the object, but some code inside the function may require Module.


A better pattern could be:

// global code
if (!iwindow.Module) window.Module = {};

(function () {
  // use Module
}());
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top