When considering whether or not to make permanent changes to the value of global_variable
, it may be wise to opt for the first example in certain situations. For instance, executing this code will only modify the local copy while leaving the global variable unaffected.
global_variable=true; (function(i){ i=false; return i; }(global_variable));
In contrast, the following code directly modifies global_variable
:
global_variable=true; (function(){ global_variable=false; }());
It's worth noting that although this variation may appear to alter the global variable, it actually does not due to the creation of a shadow copy when the function is called. This pattern should generally be avoided as it can lead to confusion:
g=true; (function(g){ g=false; return g; }(g));