Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the point in setting something equal to itself?

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)
}
like image 828
qwertynl Avatar asked Dec 04 '25 22:12

qwertynl


1 Answers

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.

like image 170
T.J. Crowder Avatar answered Dec 06 '25 13:12

T.J. Crowder



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!