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)
}
That bit does two things:
The
window.Module || {}bit uses JavaScript's curiously-powerful||operator to evaluate to eitherwindow.Module(if it's truthy) or{}(ifwindow.Moduleis falsey).||evalutes to its first non-falsey operand. Then the result of that is assigned towindow.Module. The result is that ifwindow.Modulewas falsey (probablyundefined), 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.Then it passes the result of the assignment (the value [now] in
window.Module) into the function.So the end result is that
window.Moduleis set to a new blank object if it wasn't set before, and regardless of whether it was set before, whatever object is (now) inwindow.Moduleis passed into the function.