When should I use the syntax "(function() {...})();"?
javascript
Solution
This is done to avoid naming conflicts.
When you declare a function, that function has its own namespace for variables. By wrapping the code in a function that is immediately invoked, you avoid overwriting global variables with your own values.
In this case `s` and `sc` are assigned a value. If you did that at the global scope and other scripts were already using variables with those names for a different purpose, that would cause those other scripts to fail. By introducing the new scope, the identifiers `s` and `sc` now refer to different (locally-bound) variables than the variables named `s` and `sc` that exist at the global scope.
Problem
My query is used in cases that "(function() {...})();" Given that I am not a plugin. For example "http://piecesofrakesh.blogspot.com/2009/03/downloading-javascript-files-in.html" ``` (function() { var s = [ "/javascripts/script1.js", "/javascripts/script2.js" ]; var sc = "script", tp = "text/javascript", sa = "setAttribute", doc = document, ua = window.navigator.userAgent; for(var i=0, l=s.length; i<l; ++i) { if(ua.indexOf("MSIE")!==-1 || ua.indexOf("WebKit")!==-1) { doc.writeln("<" + sc + " type=\"" + tp + "\" src=\"" + s[i] + "\" defer></" + sc + ">"); } else { var t=doc.createElement(sc); t[sa]("src", s[i]); t[sa]("type", tp); doc.getElementsByTagName("head")[0].appendChild(t); } } })(); ``` Or ``` var s = [ "/javascripts/script1.js", "/javascripts/script2.js" ]; ... ``` Thank you.