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 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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With